1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.tradefed.log;
17 
18 import com.android.tradefed.config.Option;
19 import com.android.tradefed.config.OptionClass;
20 import com.android.tradefed.config.OptionCopier;
21 import com.android.tradefed.result.ByteArrayInputStreamSource;
22 import com.android.tradefed.result.FileInputStreamSource;
23 import com.android.tradefed.result.InputStreamSource;
24 
25 import java.io.File;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 
29 /** A {@link ILeveledLogOutput} that directs log messages to stdout and to a single log file. */
30 @OptionClass(alias = "simple-file")
31 public class SimpleFileLogger extends BaseStreamLogger<FileOutputStream> {
32 
33     @Option(name = "path", description = "File path to log to.", mandatory = true)
34     private File mFile;
35 
36     @Override
init()37     public void init() throws IOException {
38         mFile.getParentFile().mkdirs();
39         mOutputStream = new FileOutputStream(mFile, true);
40     }
41 
42     @Override
getLog()43     public InputStreamSource getLog() {
44         if (mFile != null) {
45             return new FileInputStreamSource(mFile);
46         }
47         return new ByteArrayInputStreamSource(new byte[0]);
48     }
49 
50     @Override
clone()51     public SimpleFileLogger clone() {
52         SimpleFileLogger logger = new SimpleFileLogger();
53         OptionCopier.copyOptionsNoThrow(this, logger);
54         return logger;
55     }
56 }
57