quill
ConsoleSink.h
1 
7 #pragma once
8 
9 #include "quill/core/Attributes.h"
10 #include "quill/core/LogLevel.h"
11 #include "quill/sinks/StreamSink.h"
12 
13 #include <array>
14 #include <cstdint>
15 #include <cstdio>
16 #include <cstring>
17 #include <string>
18 #include <string_view>
19 #include <utility>
20 #include <vector>
21 
22 #if defined(_WIN32)
23  #if !defined(WIN32_LEAN_AND_MEAN)
24  #define WIN32_LEAN_AND_MEAN
25  #endif
26 
27  #if !defined(NOMINMAX)
28  // Mingw already defines this, so no need to redefine
29  #define NOMINMAX
30  #endif
31 
32  #include <io.h>
33  #include <windows.h>
34 #else
35  #include <cstdlib>
36  #include <unistd.h>
37 #endif
38 
39 QUILL_BEGIN_NAMESPACE
40 
42 class MacroMetadata;
43 
45 {
46 public:
47  enum class ColourMode
48  {
49  Always,
50  Automatic,
51  Never
52  };
53 
57  class Colours
58  {
59  public:
60  Colours() { apply_default_colours(); }
61 
62  ~Colours() = default;
63 
67  void apply_default_colours() noexcept
68  {
69  assign_colour_to_log_level(LogLevel::TraceL3, white);
70  assign_colour_to_log_level(LogLevel::TraceL2, white);
71  assign_colour_to_log_level(LogLevel::TraceL1, white);
72  assign_colour_to_log_level(LogLevel::Debug, cyan);
73  assign_colour_to_log_level(LogLevel::Info, green);
74  assign_colour_to_log_level(LogLevel::Notice, white_bold);
75  assign_colour_to_log_level(LogLevel::Warning, yellow_bold);
76  assign_colour_to_log_level(LogLevel::Error, red_bold);
77  assign_colour_to_log_level(LogLevel::Critical, bold_on_red);
78  assign_colour_to_log_level(LogLevel::Backtrace, magenta);
79  }
80 
86  void assign_colour_to_log_level(LogLevel log_level, std::string_view colour) noexcept
87  {
88  auto const log_lvl = static_cast<uint32_t>(log_level);
89  _log_level_colours[log_lvl] = colour;
90  _colours_enabled = true;
91  }
92 
93  QUILL_ATTRIBUTE_COLD void set_colours_enabled(bool value) { _colours_enabled = value; }
94 
98  QUILL_NODISCARD bool colours_enabled() const noexcept
99  {
100  return _colour_output_supported && _colours_enabled;
101  }
102 
108  QUILL_NODISCARD std::string_view log_level_colour(LogLevel log_level) const noexcept
109  {
110  auto const log_lvl = static_cast<uint32_t>(log_level);
111  return _log_level_colours[log_lvl];
112  }
113 
114  // Formatting codes
115  static constexpr std::string_view reset{"\033[0m"};
116  static constexpr std::string_view bold{"\033[1m"};
117  static constexpr std::string_view dark{"\033[2m"};
118  static constexpr std::string_view underline{"\033[4m"};
119  static constexpr std::string_view blink{"\033[5m"};
120  static constexpr std::string_view reverse{"\033[7m"};
121  static constexpr std::string_view concealed{"\033[8m"};
122  static constexpr std::string_view clear_line{"\033[K"};
123 
124  // Foreground colors
125  static constexpr std::string_view black{"\033[30m"};
126  static constexpr std::string_view red{"\033[31m"};
127  static constexpr std::string_view green{"\033[32m"};
128  static constexpr std::string_view yellow{"\033[33m"};
129  static constexpr std::string_view blue{"\033[34m"};
130  static constexpr std::string_view magenta{"\033[35m"};
131  static constexpr std::string_view cyan{"\033[36m"};
132  static constexpr std::string_view white{"\033[37m"};
133 
135  static constexpr std::string_view on_black{"\033[40m"};
136  static constexpr std::string_view on_red{"\033[41m"};
137  static constexpr std::string_view on_green{"\033[42m"};
138  static constexpr std::string_view on_yellow{"\033[43m"};
139  static constexpr std::string_view on_blue{"\033[44m"};
140  static constexpr std::string_view on_magenta{"\033[45m"};
141  static constexpr std::string_view on_cyan{"\033[46m"};
142  static constexpr std::string_view on_white{"\033[47m"};
143 
145  static constexpr std::string_view white_bold{"\033[97m\033[1m"};
146  static constexpr std::string_view yellow_bold{"\033[33m\033[1m"};
147  static constexpr std::string_view red_bold{"\033[31m\033[1m"};
148  static constexpr std::string_view bold_on_red{"\033[1m\033[41m"};
149 
150  private:
151  friend class ConsoleSink;
152 
153  /***/
154  QUILL_NODISCARD QUILL_ATTRIBUTE_COLD static bool _supports_colour_output() noexcept
155  {
156 #ifdef _WIN32
157  // On Windows 10 and later, ANSI colors are supported
158  return true;
159 #else
160  // Get term from env
161  auto* env_p = std::getenv("TERM");
162 
163  if (env_p == nullptr)
164  {
165  return false;
166  }
167 
168  static constexpr char const* terms[] = {
169  "ansi", "color", "console", "cygwin", "gnome",
170  "konsole", "kterm", "linux", "msys", "putty",
171  "rxvt", "screen", "vt100", "xterm", "tmux",
172  "terminator", "alacritty", "gnome-terminal", "xfce4-terminal", "lxterminal",
173  "mate-terminal", "uxterm", "eterm", "tilix", "rxvt-unicode",
174  "kde-konsole"};
175 
176  // Loop through each term and check if it's found in env_p
177  for (char const* term : terms)
178  {
179  if (std::strstr(env_p, term) != nullptr)
180  {
181  // term found
182  return true;
183  }
184  }
185 
186  // none of the terms are found
187  return false;
188 #endif
189  }
190 
191  /***/
192  QUILL_NODISCARD QUILL_ATTRIBUTE_COLD static bool _is_terminal_output(FILE* file) noexcept
193  {
194 #ifdef _WIN32
195  return _isatty(_fileno(file)) != 0;
196 #else
197  return ::isatty(fileno(file)) != 0;
198 #endif
199  }
200 
201 #ifdef _WIN32
202  /***/
203  QUILL_ATTRIBUTE_COLD void _activate_ansi_support(FILE* file) const
204  {
205  if (!_colour_output_supported)
206  {
207  return;
208  }
209 
210  // Try to enable ANSI support for Windows console
211  auto const out_handle = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(file)));
212  if (out_handle == INVALID_HANDLE_VALUE)
213  {
214  return;
215  }
216 
217  DWORD dw_mode = 0;
218  if (!GetConsoleMode(out_handle, &dw_mode))
219  {
220  return;
221  }
222 
223  dw_mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
224  dw_mode |= ENABLE_PROCESSED_OUTPUT;
225 
226  SetConsoleMode(out_handle, dw_mode);
227  }
228 #endif
229 
230  /***/
231  void _configure_colour_support(FILE* file, ColourMode colour_mode) noexcept
232  {
233  if (colour_mode == ColourMode::Always)
234  {
235  _colour_output_supported = true;
236  }
237  else if (colour_mode == ColourMode::Automatic)
238  {
239  _colour_output_supported = _is_terminal_output(file) && _supports_colour_output();
240  }
241  else
242  {
243  _colour_output_supported = false;
244  }
245 
246 #ifdef _WIN32
247  // Enable ANSI color support on Windows
248  _activate_ansi_support(file);
249 #endif
250  }
251 
252  private:
253  std::array<std::string_view, 10> _log_level_colours;
254  bool _colours_enabled{true};
255  bool _colour_output_supported{false};
256  };
257 
266  QUILL_ATTRIBUTE_COLD void set_colours(Colours colours) { _colours = colours; }
267 
282  QUILL_ATTRIBUTE_COLD void set_colour_mode(ColourMode colour_mode) { _colour_mode = colour_mode; }
283 
296  QUILL_ATTRIBUTE_COLD void set_stream(std::string const& stream) { _stream = stream; }
297 
307  QUILL_ATTRIBUTE_COLD void set_override_pattern_formatter_options(std::optional<PatternFormatterOptions> const& options)
308  {
309  _override_pattern_formatter_options = options;
310  }
311 
313  QUILL_NODISCARD Colours const& colours() noexcept { return _colours; }
314  QUILL_NODISCARD ColourMode colour_mode() const noexcept { return _colour_mode; }
315  QUILL_NODISCARD std::string const& stream() const noexcept { return _stream; }
316  QUILL_NODISCARD std::optional<PatternFormatterOptions> const& override_pattern_formatter_options() const noexcept
317  {
318  return _override_pattern_formatter_options;
319  }
320 
321 private:
322  friend class ConsoleSink;
323 
324  std::optional<PatternFormatterOptions> _override_pattern_formatter_options;
325  std::string _stream = "stdout";
326  Colours _colours;
327  ColourMode _colour_mode{ColourMode::Automatic};
328 };
329 
330 /***/
331 class ConsoleSink : public StreamSink
332 {
333 public:
338  explicit ConsoleSink(ConsoleSinkConfig const& config = ConsoleSinkConfig{},
339  FileEventNotifier file_event_notifier = FileEventNotifier{})
340  : StreamSink{config.stream(), nullptr, config.override_pattern_formatter_options(),
341  std::move(file_event_notifier)},
342  _config(config)
343  {
344  QUILL_ASSERT(_config.stream() == "stdout" || config.stream() == "stderr",
345  "Invalid stream name in ConsoleSink constructor, must be 'stdout' or 'stderr'");
346 
347  if (_config.colour_mode() == ConsoleSinkConfig::ColourMode::Never)
348  {
349  _config._colours.set_colours_enabled(false);
350  }
351  else
352  {
353  _config._colours._configure_colour_support(_file, _config.colour_mode());
354  _config._colours.set_colours_enabled(true);
355  }
356  }
357 
358  ~ConsoleSink() override = default;
359 
375  QUILL_ATTRIBUTE_HOT void write_log(MacroMetadata const* log_metadata, uint64_t log_timestamp,
376  std::string_view thread_id, std::string_view thread_name,
377  std::string const& process_id, std::string_view logger_name,
378  LogLevel log_level, std::string_view log_level_description,
379  std::string_view log_level_short_code,
380  std::vector<std::pair<std::string, std::string>> const* named_args,
381  std::string_view log_message, std::string_view log_statement) override
382  {
383  if (_config.colours().colours_enabled())
384  {
385  // Write colour code
386  std::string_view const colour_code = _config.colours().log_level_colour(log_level);
387  safe_fwrite(colour_code.data(), sizeof(char), colour_code.size(), _file);
388 
389  // Write record to file
390  StreamSink::write_log(log_metadata, log_timestamp, thread_id, thread_name, process_id,
391  logger_name, log_level, log_level_description, log_level_short_code,
392  named_args, log_message, log_statement);
393 
394  // Reset colour code
395  safe_fwrite(ConsoleSinkConfig::Colours::reset.data(), sizeof(char),
396  ConsoleSinkConfig::Colours::reset.size(), _file);
397  }
398  else
399  {
400  // Write record to file
401  StreamSink::write_log(log_metadata, log_timestamp, thread_id, thread_name, process_id,
402  logger_name, log_level, log_level_description, log_level_short_code,
403  named_args, log_message, log_statement);
404  }
405  }
406 
407 protected:
408  // protected in case someone wants to derive from this class and create a custom one, e.g. for json logging to stdout
409  ConsoleSinkConfig _config;
410 };
411 
412 QUILL_END_NAMESPACE
QUILL_ATTRIBUTE_HOT void write_log(MacroMetadata const *, uint64_t, std::string_view, std::string_view, std::string const &, std::string_view, LogLevel, std::string_view, std::string_view, std::vector< std::pair< std::string, std::string >> const *, std::string_view, std::string_view log_statement) override
Writes a formatted log message to the stream.
Definition: StreamSink.h:152
QUILL_ATTRIBUTE_COLD void set_stream(std::string const &stream)
Sets the output stream for console logging.
Definition: ConsoleSink.h:296
Definition: ConsoleSink.h:331
QUILL_ATTRIBUTE_COLD void set_colour_mode(ColourMode colour_mode)
Sets the colour mode for console output.
Definition: ConsoleSink.h:282
void assign_colour_to_log_level(LogLevel log_level, std::string_view colour) noexcept
Sets a custom colour per log level.
Definition: ConsoleSink.h:86
QUILL_ATTRIBUTE_COLD void set_override_pattern_formatter_options(std::optional< PatternFormatterOptions > const &options)
Sets custom pattern formatter options for this sink.
Definition: ConsoleSink.h:307
Captures and stores information about a logging event in compile time.
Definition: MacroMetadata.h:22
Definition: ConsoleSink.h:44
void apply_default_colours() noexcept
Sets some default colours for terminal.
Definition: ConsoleSink.h:67
QUILL_NODISCARD bool colours_enabled() const noexcept
Definition: ConsoleSink.h:98
QUILL_NODISCARD std::string_view log_level_colour(LogLevel log_level) const noexcept
The colour for the given log level.
Definition: ConsoleSink.h:108
QUILL_ATTRIBUTE_HOT void write_log(MacroMetadata const *log_metadata, uint64_t log_timestamp, std::string_view thread_id, std::string_view thread_name, std::string const &process_id, std::string_view logger_name, LogLevel log_level, std::string_view log_level_description, std::string_view log_level_short_code, std::vector< std::pair< std::string, std::string >> const *named_args, std::string_view log_message, std::string_view log_statement) override
Write a formatted log message to the stream.
Definition: ConsoleSink.h:375
Represents console colours.
Definition: ConsoleSink.h:57
QUILL_ATTRIBUTE_COLD void set_colours(Colours colours)
Sets custom colours for each log level.
Definition: ConsoleSink.h:266
Notifies on file events by calling the appropriate callback, the callback is executed on the backend ...
Definition: StreamSink.h:55
ConsoleSink(ConsoleSinkConfig const &config=ConsoleSinkConfig{}, FileEventNotifier file_event_notifier=FileEventNotifier{})
Constructor with custom ConsoleColours config.
Definition: ConsoleSink.h:338
StreamSink class for handling log messages.
Definition: StreamSink.h:67
QUILL_NODISCARD Colours const & colours() noexcept
Getters.
Definition: ConsoleSink.h:313