ifm3d
log_writer_console_colored.h
1 // -*- c++ -*-
2 /*
3  * Copyright 2023-present ifm electronic, gmbh
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifndef IFM3D_COMMON_LOGGING_LOG_WRITER_CONSOLE_COLORED_H
8 #define IFM3D_COMMON_LOGGING_LOG_WRITER_CONSOLE_COLORED_H
9 
10 #include <ifm3d/common/logging/log_writer_console.h>
11 
12 namespace ifm3d
13 {
14  template <class Formatter,
15  typename std::enable_if_t<std::is_same_v<
16  decltype(Formatter::format(
17  ifm3d::LogEntry("", ifm3d::LogLevel::Info, "", "", 1))),
18  std::string>>* = nullptr>
19  class LogWriterConsoleColored : public LogWriterConsole<Formatter>
20  {
21  public:
22  LogWriterConsoleColored(Output out = Output::StdErr)
24  {}
25 
26  void
27  Write(const LogEntry& entry) override
28  {
29  if (this->is_a_tty_)
30  {
31  const auto str = Formatter::format(entry);
32  const std::lock_guard<std::mutex> lock(this->mutex_);
33  this->SetColor(entry.GetLogLevel());
34  this->out_ << str;
35  this->ResetColor();
36  this->out_ << std::endl;
37  }
38  else
39  {
41  }
42  }
43 
44  protected:
45  void
46  SetColor(LogLevel log_level)
47  {
48  switch (log_level)
49  {
50  case LogLevel::Critical:
51  this->out_ << "\x1B[97m\x1B[41m"; // white on red background
52  break;
53 
54  case LogLevel::Error:
55  this->out_ << "\x1B[91m"; // red
56  break;
57 
58  case LogLevel::Warning:
59  this->out_ << "\x1B[93m"; // yellow
60  break;
61 
62  case LogLevel::Debug:
63  case LogLevel::Verbose:
64  this->out_ << "\x1B[96m"; // cyan
65  break;
66  default:
67  break;
68  }
69  }
70 
71  void
72  ResetColor()
73  {
74  this->out_ << "\x1B[0m\x1B[0K";
75  }
76  };
77 }
78 #endif // IFM3D_COMMON_LOGGING_LOG_WRITER_CONSOLE_COLORED_H
ifm3d::LogEntry
Definition: log_entry.h:19
ifm3d::LogWriterConsole
Definition: log_writer_console.h:38
ifm3d::LogWriterConsoleColored
Definition: log_writer_console_colored.h:19