1 /*
2  * Copyright (C) 2020 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 
17 #ifndef IORAP_UTILS_PRINTER_H_
18 #define IORAP_UTILS_PRINTER_H_
19 
20 #include <utils/Printer.h>
21 
22 #include <string.h>
23 
24 namespace iorap::common {
25 
26 class StderrLogPrinter : public ::android::Printer {
27 public:
28     // Create a printer using the specified logcat and log priority
29     // - Unless ignoreBlankLines is false, print blank lines to logcat
30     // (Note that the default ALOG behavior is to ignore blank lines)
31     StderrLogPrinter(const char* logtag,
32                      android_LogPriority priority = ANDROID_LOG_DEBUG,
33                      const char* prefix = nullptr,
34                      bool ignore_blank_lines = false)
35       : log_printer_{logtag, priority, prefix, ignore_blank_lines} {
36       logtag_ = logtag;
37       prefix_ = prefix;
38       ignore_blank_lines_ = ignore_blank_lines;
39     }
40 
41     // Print the specified line to logcat. No \n at the end is necessary.
printLine(const char * string)42     virtual void printLine(const char* string) override {
43       if (ignore_blank_lines_ && strlen(string) == 0) {
44         return;
45       }
46       std::cerr << logtag_ << ": ";
47       if (prefix_ != nullptr) {
48         std::cerr << prefix_;
49       }
50       std::cerr << string << std::endl;
51       log_printer_.printLine(string);
52     }
53  private:
54     ::android::LogPrinter log_printer_;
55     const char* logtag_;
56     const char* prefix_;
57     bool ignore_blank_lines_;
58 };
59 
60 }  // namespace iorap::common
61 
62 #endif  // IORAP_UTILS_PRINTER_H_
63