1 // Copyright (C) 2021 The Android Open Source Project 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #pragma once 16 17 #include <stdio.h> 18 19 #include <iostream> 20 #include <sstream> 21 #include <string> 22 #include <vector> 23 24 namespace dittosuite { 25 26 enum class LogLevel { kVerbose, kDebug, kInfo, kWarning, kError, kFatal }; 27 28 enum class LogStream { kStdout, kLogcat }; 29 30 class Logger { 31 public: 32 Logger(Logger const&) = delete; 33 void operator=(Logger const&) = delete; 34 static Logger& GetInstance(); 35 void SetLogLevel(LogLevel log_level); 36 void SetLogStream(LogStream log_stream); 37 LogLevel GetLogLevel() const; 38 LogStream GetLogStream() const; 39 void WriteLogMessage(LogLevel log_level, const std::string& message, const std::string& file_name, 40 int line, bool print_errno); 41 42 protected: Logger()43 Logger() : log_level_(LogLevel::kInfo) {} 44 45 private: 46 LogLevel log_level_; 47 LogStream log_stream_; 48 }; 49 50 LogLevel ArgToLogLevel(const std::string_view optarg); 51 52 } // namespace dittosuite 53 54 #define DITTO_LOGGER dittosuite::Logger::GetInstance() 55 56 #define DITTO_LOG(VERBOSITY, X, print_errno) \ 57 do { \ 58 if (DITTO_LOGGER.GetLogLevel() <= dittosuite::LogLevel::VERBOSITY) { \ 59 DITTO_LOGGER.WriteLogMessage(dittosuite::LogLevel::VERBOSITY, X, __FILE__, __LINE__, \ 60 print_errno); \ 61 } \ 62 } while (false) 63 64 #define LOGF(X) \ 65 do { \ 66 DITTO_LOG(kFatal, X, false); \ 67 exit(EXIT_FAILURE); \ 68 } while (false) 69 #define LOGE(X) DITTO_LOG(kError, X, false) 70 #define LOGW(X) DITTO_LOG(kWarning, X, false) 71 #define LOGI(X) DITTO_LOG(kInfo, X, false) 72 #define LOGD(X) DITTO_LOG(kDebug, X, false) 73 #define LOGV(X) DITTO_LOG(kVerbose, X, false) 74 75 #define PLOGF(X) \ 76 do { \ 77 DITTO_LOG(kFatal, X, true); \ 78 exit(EXIT_FAILURE); \ 79 } while (false) 80 #define PLOGE(X) DITTO_LOG(kError, X, true) 81 #define PLOGW(X) DITTO_LOG(kWarning, X, true) 82 #define PLOGI(X) DITTO_LOG(kInfo, X, true) 83 #define PLOGD(X) DITTO_LOG(kDebug, X, true) 84 #define PLOGV(X) DITTO_LOG(kVerbose, X, true) 85