The Battle for Wesnoth  1.17.17+dev
log.hpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2004 - 2023
3  by Guillaume Melquiond <guillaume.melquiond@gmail.com>
4  Copyright (C) 2003 by David White <dave@whitevine.net>
5  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
6 
7  This program is free software; you can redistribute it and/or modify
8  it under the terms of the GNU General Public License as published by
9  the Free Software Foundation; either version 2 of the License, or
10  (at your option) any later version.
11  This program is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY.
13 
14  See the COPYING file for more details.
15 */
16 
17 /**
18  * @file
19  * Standard logging facilities (interface).
20  *
21  * To use one of the standard log channels, put something like the following at the start
22  * of your .cpp file:
23  *
24  * static lg::log_domain log_display("display");
25  * \#define ERR_DP LOG_STREAM(err, log_display)
26  * \#define LOG_DP LOG_STREAM(info, log_display)
27  *
28  * Then stream logging info to ERR_DP, or LOG_DP, as if it were an ostream like std::cerr.
29  * (In general it will actually be std::cerr at runtime when logging is enabled.)
30  *
31  * LOG_DP << "Found a window resize event: ...";
32  *
33  * Please do not use iomanip features like std::hex directly on the logger. Because of the
34  * design of the logger, this will result in all of the loggers (in fact std::cerr) being
35  * imbued with std::hex. Please use a formatter instead.
36  *
37  * \#include "formatter.hpp"
38  *
39  * LOG_DP << (formatter() << "The random seed is: '" << std::hex << seed << "'\n").str();
40  *
41  * It might be nice if somehow the logger class / macros could support using iomanip
42  * things directly, but right now it doesn't, and it seems that it would complicate the
43  * design greatly enough that it doesn't seem worth it.
44  */
45 
46 #pragma once
47 
48 #ifndef __func__
49  #ifdef __FUNCTION__
50  #define __func__ __FUNCTION__
51  #endif
52 #endif
53 
54 #include <iosfwd> // needed else all files including log.hpp need to do it.
55 #include <optional>
56 #include <sstream> // as above. iostream (actually, iosfwd) declares stringstream as an incomplete type, but does not define it
57 #include <string>
58 #include <utility>
59 #include <ctime>
60 
61 #include "formatter.hpp"
62 
63 namespace lg {
64 
65 // Prefix and extension for log files. This is used both to generate the unique
66 // log file name during startup and to find old files to delete.
67 const std::string log_file_prefix = "wesnoth-";
68 const std::string log_file_suffix = ".log";
69 
70 // Maximum number of older log files to keep intact. Other files are deleted.
71 // Note that this count does not include the current log file!
72 const unsigned max_logs = 8;
73 
75 {
79  LG_DEBUG=3
80 };
81 
82 /**
83  * Helper class to redirect the output of the logger in a certain scope.
84  *
85  * The main usage of the redirection is for the unit tests to validate the
86  * output on the logger with the expected output.
87  */
89 {
90 public:
91 
92  /**
93  * Constructor.
94  *
95  * @param stream The stream to direct the output to.
96  */
97  explicit redirect_output_setter(std::ostream& stream);
98 
100 
101 private:
102 
103  /**
104  * The previously set redirection.
105  *
106  * This value is stored here to be restored in this destructor.
107  */
108  std::ostream* old_stream_;
109 };
110 
111 class logger;
112 
113 typedef std::pair<const std::string, int> logd;
114 
115 class log_domain {
117 public:
118  explicit log_domain(char const *name, int severity = 1);
119  friend class logger;
120 };
121 
122 bool set_log_domain_severity(const std::string& name, int severity);
123 bool set_log_domain_severity(const std::string& name, const logger &lg);
124 bool get_log_domain_severity(const std::string& name, int &severity);
125 std::string list_logdomains(const std::string& filter);
126 
127 void set_strict_severity(int severity);
128 void set_strict_severity(const logger &lg);
129 bool broke_strict();
130 void set_log_to_file();
132 std::optional<bool> log_dir_writable();
133 
134 bool is_not_log_file(const std::string& filename);
135 void rotate_logs(const std::string& log_dir);
136 std::string unique_log_filename();
137 
138 // A little "magic" to surround the logging operation in a mutex.
139 // This works by capturing the output first to a stringstream formatter, then
140 // locking a mutex and dumping it to the stream all in one go.
141 // By doing this we can avoid rare deadlocks if a function whose output is streamed
142 // calls logging of its own.
143 // We overload operator| only because it has lower precedence than operator<<
144 // Any other lower-precedence operator would have worked just as well.
146  std::ostream& stream_;
147  int indent_ = 0;
148  bool timestamp_ = false;
149  std::string prefix_;
150  bool auto_newline_ = true;
151 public:
152  log_in_progress(std::ostream& stream);
153  void operator|(formatter&& message);
154  void set_indent(int level);
155  void enable_timestamp();
156  void set_prefix(const std::string& prefix);
157  void set_auto_newline(bool enabled);
158 };
159 
160 class logger {
161  char const *name_;
163 public:
164  logger(char const *name, int severity): name_(name), severity_(severity) {}
165  log_in_progress operator()(const log_domain& domain,
166  bool show_names = true, bool do_indent = false, bool show_timestamps = true, bool break_strict = true, bool auto_newline = true) const;
167 
168  bool dont_log(const log_domain& domain) const
169  {
170  return severity_ > domain.domain_->second;
171  }
172 
173  /**
174  * Returns following values depending on the logger:
175  * error: 0
176  * warn: 1
177  * info: 2
178  * debug: 3
179  * See also the lg::severity enum.
180  */
181  int get_severity() const
182  {
183  return severity_;
184  }
185 
186  std::string get_name() const
187  {
188  return name_;
189  }
190 };
191 
192 void timestamps(bool);
193 void precise_timestamps(bool);
194 std::string get_timestamp(const std::time_t& t, const std::string& format="%Y%m%d %H:%M:%S ");
195 std::string get_timespan(const std::time_t& t);
196 std::string sanitize_log(const std::string& logstr);
197 std::string& get_log_file_path();
198 void set_log_file_path(const std::string& path);
199 
200 logger &err(), &warn(), &info(), &debug();
201 log_domain& general();
202 
204 {
205  int64_t ticks_;
207  std::string str_;
208 public:
209  scope_logger(const log_domain& domain, const char* str)
210  : ticks_(0)
211  , domain_(domain)
212  , str_()
213  {
214  if (!debug().dont_log(domain)) do_log_entry(str);
215  }
216  scope_logger(const log_domain& domain, const std::string& str)
217  : ticks_(0)
218  , domain_(domain)
219  , str_()
220  {
221  if (!debug().dont_log(domain)) do_log_entry(str);
222  }
224  {
225  if (!str_.empty()) do_log_exit();
226  }
227 private:
228  void do_log_entry(const std::string& str) noexcept;
229  void do_log_exit() noexcept;
230 };
231 
232 /**
233  * Use this to show WML errors in the ingame chat.
234  * After every WML event the errors are shown to the user so they can inform the campaign maintainer.
235  */
236 std::stringstream& log_to_chat();
237 
238 } // namespace lg
239 
240 #define log_scope(description) lg::scope_logger scope_logging_object__(lg::general(), description);
241 #define log_scope2(domain,description) lg::scope_logger scope_logging_object__(domain, description);
242 
243 #define LOG_STREAM(level, domain) if (lg::level().dont_log(domain)) ; else lg::level()(domain) | formatter()
244 
245 // Don't prefix the logdomain to messages on this stream
246 #define LOG_STREAM_NAMELESS(level, domain) if (lg::level().dont_log(domain)) ; else lg::level()(domain, false) | formatter()
247 
248 // Like LOG_STREAM_NAMELESS except doesn't add newlines automatically
249 #define LOG_STREAM_NAMELESS_STREAMING(level, domain) if (lg::level().dont_log(domain)) ; else lg::level()(domain, false, false, true, true, false) | formatter()
250 
251 // When using log_scope/log_scope2 it is nice to have all output indented.
252 #define LOG_STREAM_INDENT(level,domain) if (lg::level().dont_log(domain)) ; else lg::level()(domain, true, true) | formatter()
253 
254 // If you have an explicit logger object and want to ignore the logging level, use this.
255 // Meant for cases where you explicitly call dont_log to avoid an expensive operation if the logging is disabled.
256 #define FORCE_LOG_TO(logger, domain) logger(domain) | formatter()
257 
258 // always log (since it's at the error level) to the general log stream
259 // outputting the log domain and timestamp is disabled
260 // meant as a replacement to using cerr/cout, but that goes through the same logging infrastructure as everything else
261 #define PLAIN_LOG lg::err()(lg::general(), false, false, false, false, true) | formatter()
262 #define STREAMING_LOG lg::err()(lg::general(), false, false, false, false, false) | formatter()
double t
Definition: astarsearch.cpp:65
std::ostringstream wrapper.
Definition: formatter.hpp:40
logd * domain_
Definition: log.hpp:116
log_domain(char const *name, int severity=1)
Definition: log.cpp:251
void operator|(formatter &&message)
Definition: log.cpp:405
std::string prefix_
Definition: log.hpp:149
std::ostream & stream_
Definition: log.hpp:146
void set_auto_newline(bool enabled)
Definition: log.cpp:435
void set_prefix(const std::string &prefix)
Definition: log.cpp:431
void enable_timestamp()
Definition: log.cpp:427
bool auto_newline_
Definition: log.hpp:150
void set_indent(int level)
Definition: log.cpp:423
log_in_progress(std::ostream &stream)
Definition: log.cpp:401
char const * name_
Definition: log.hpp:161
std::string get_name() const
Definition: log.hpp:186
int get_severity() const
Returns following values depending on the logger: error: 0 warn: 1 info: 2 debug: 3 See also the lg::...
Definition: log.hpp:181
log_in_progress operator()(const log_domain &domain, bool show_names=true, bool do_indent=false, bool show_timestamps=true, bool break_strict=true, bool auto_newline=true) const
Definition: log.cpp:371
int severity_
Definition: log.hpp:162
logger(char const *name, int severity)
Definition: log.hpp:164
bool dont_log(const log_domain &domain) const
Definition: log.hpp:168
Helper class to redirect the output of the logger in a certain scope.
Definition: log.hpp:89
std::ostream * old_stream_
The previously set redirection.
Definition: log.hpp:108
redirect_output_setter(std::ostream &stream)
Constructor.
Definition: log.cpp:203
const log_domain & domain_
Definition: log.hpp:206
void do_log_entry(const std::string &str) noexcept
Definition: log.cpp:439
std::string str_
Definition: log.hpp:207
scope_logger(const log_domain &domain, const char *str)
Definition: log.hpp:209
void do_log_exit() noexcept
Definition: log.cpp:449
scope_logger(const log_domain &domain, const std::string &str)
Definition: log.hpp:216
int64_t ticks_
Definition: log.hpp:205
std::string path
Definition: filesystem.cpp:83
Definition: pump.hpp:41
logger & err()
Definition: log.cpp:220
severity
Definition: log.hpp:75
@ LG_INFO
Definition: log.hpp:78
@ LG_DEBUG
Definition: log.hpp:79
@ LG_WARN
Definition: log.hpp:77
@ LG_ERROR
Definition: log.hpp:76
log_domain & general()
Definition: log.cpp:246
bool broke_strict()
Definition: log.cpp:313
std::string get_timespan(const std::time_t &t)
Definition: log.cpp:324
logger & debug()
Definition: log.cpp:238
void set_strict_severity(int severity)
Definition: log.cpp:303
void rotate_logs(const std::string &log_dir)
Deletes old log files from the log directory.
Definition: log.cpp:93
std::string unique_log_filename()
Generates a unique log file name.
Definition: log.cpp:127
void set_log_to_file()
Definition: log.cpp:173
void set_log_file_path(const std::string &path)
Definition: log.cpp:198
logger & warn()
Definition: log.cpp:226
std::string list_logdomains(const std::string &filter)
Definition: log.cpp:293
bool is_not_log_file(const std::string &fn)
Helper function for rotate_logs.
Definition: log.cpp:84
void timestamps(bool t)
Definition: log.cpp:217
bool set_log_domain_severity(const std::string &name, int severity)
Definition: log.cpp:260
std::string sanitize_log(const std::string &logstr)
Definition: log.cpp:353
const unsigned max_logs
Definition: log.hpp:72
void check_log_dir_writable()
Definition: log.cpp:141
std::stringstream & log_to_chat()
Use this to show WML errors in the ingame chat.
Definition: log.cpp:462
const std::string log_file_prefix
Definition: log.hpp:67
std::string & get_log_file_path()
Definition: log.cpp:194
std::pair< const std::string, int > logd
Definition: log.hpp:111
std::string get_timestamp(const std::time_t &t, const std::string &format)
Definition: log.cpp:317
void precise_timestamps(bool pt)
Definition: log.cpp:218
std::optional< bool > log_dir_writable()
Definition: log.cpp:189
bool get_log_domain_severity(const std::string &name, int &severity)
Definition: log.cpp:284
logger & info()
Definition: log.cpp:232
const std::string log_file_suffix
Definition: log.hpp:68