The Battle for Wesnoth 1.21.0-dev
 
Loading...
Searching...
No Matches
log.cpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2004 - 2025
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 (implementation).
20 * See also the command line switches --logdomains and --log-@<level@>="domain".
21 */
22
23#include "log.hpp"
24#include "filesystem.hpp"
25#include "mt_rng.hpp"
28#include "utils/general.hpp"
29
30#include <boost/algorithm/string.hpp>
31
32#include <map>
33#include <mutex>
34#include <iostream>
35#include <iomanip>
36
37#ifdef __ANDROID__
38#include <android/log.h>
39#endif
40
41#ifdef _WIN32
42#include <io.h>
43#endif
44
45static lg::log_domain log_setup("logsetup");
46#define ERR_LS LOG_STREAM(err, log_setup)
47#define WRN_LS LOG_STREAM(warn, log_setup)
48#define LOG_LS LOG_STREAM(info, log_setup)
49#define DBG_LS LOG_STREAM(debug, log_setup)
50
51namespace {
52
53class null_streambuf : public std::streambuf
54{
55 virtual int overflow(int c) { return std::char_traits< char >::not_eof(c); }
56public:
57 null_streambuf() {}
58};
59
60#ifdef __ANDROID__
61class android_log_buf : public std::streambuf
62{
63 std::string output;
64 void write() {
65 auto newline { output.find_first_of("\n") };
66 while(newline != std::string::npos) {
67 __android_log_write(ANDROID_LOG_INFO, "wesnoth", output.substr(0, newline).c_str());
68 output = output.substr(newline+1);
69 newline = output.find_first_of("\n");
70 }
71 }
72protected:
73 virtual std::streamsize xsputn(const char_type* s, std::streamsize n) override {
74 output.append(s, n);
75 write();
76 return n;
77 }
78 virtual int_type overflow(int_type ch) override {
79 output.push_back(ch);
80 write();
81 return 1;
82 }
83};
84#endif
85
86} // end anonymous namespace
87
88static std::ostream null_ostream(new null_streambuf);
89static int indent = 0;
90static bool timestamp = true;
91static bool precise_timestamp = false;
92static std::mutex log_mutex;
93
94static bool log_sanitization = true;
95
96/** whether the current logs directory is writable */
97static utils::optional<bool> is_log_dir_writable_ = utils::nullopt;
98/** alternative stream to write data to */
99static std::ostream *output_stream_ = nullptr;
100
101/**
102 * @return std::cerr if the redirect_output_setter isn't being used, output_stream_ if it is
103 */
104static std::ostream& output()
105{
106#ifdef __ANDROID__
107 static std::ostream android_ostream(new android_log_buf);
108 return android_ostream;
109#endif
110 if(output_stream_) {
111 return *output_stream_;
112 }
113 return std::cerr;
114}
115
116/** path to the current log file; does not include the extension */
117static std::string output_file_path_ = "";
118/** path to the current logs directory; may change after being initially set if a custom userdata directory is given on the command line */
119static std::string logs_dir_ = "";
120
121namespace lg {
122
123std::ostringstream& operator<<(std::ostringstream& oss, const lg::severity severity)
124{
125 oss << static_cast<int>(severity);
126 return oss;
127}
128
129bool is_not_log_file(const std::string& fn)
130{
131 return !(boost::algorithm::istarts_with(fn, lg::log_file_prefix) &&
132 boost::algorithm::iends_with(fn, lg::log_file_suffix));
133}
134
135void rotate_logs(const std::string& log_dir)
136{
137 // if logging to file is disabled, don't rotate the logs
138 if(output_file_path_.empty()) {
139 return;
140 }
141
142 std::vector<std::string> files;
143 filesystem::get_files_in_dir(log_dir, &files);
144
146
147 if(files.size() <= lg::max_logs) {
148 return;
149 }
150
151 // Sorting the file list and deleting all but the last max_logs items
152 // should hopefully be faster than stat'ing every single file for its
153 // time attributes (which aren't very reliable to begin with).
154
155 std::sort(files.begin(), files.end());
156
157 for(std::size_t j = 0; j < files.size() - lg::max_logs; ++j) {
158 const std::string path = log_dir + '/' + files[j];
159 LOG_LS << "rotate_logs(): delete " << path;
160 if(!filesystem::delete_file(path)) {
161 ERR_LS << "rotate_logs(): failed to delete " << path << "!";
162 }
163 }
164}
165
167{
168 std::ostringstream o;
169 const auto now = std::chrono::system_clock::now();
171
173 << chrono::format_local_timestamp(now, "%Y%m%d-%H%M%S-")
174 << rng.get_next_random();
175
176 return o.str();
177}
178
180{
181 std::string dummy_log = filesystem::get_logs_dir()+"/dummy.log";
182
183 // log directory doesn't exist and can't be created
185 is_log_dir_writable_ = false;
186 return;
187 }
188
189 // can't create and write new log files
190 try {
191 filesystem::write_file(dummy_log, " ");
192 } catch(const filesystem::io_exception&) {
193 is_log_dir_writable_ = false;
194 return;
195 }
196
197 // confirm that file exists and was written to
198 if(filesystem::file_size(dummy_log) != 1) {
199 is_log_dir_writable_ = false;
200 }
201
202 // can't delete files - prevents log rotation
203 if(filesystem::file_exists(dummy_log) && !filesystem::delete_file(dummy_log)) {
204 is_log_dir_writable_ = false;
205 return;
206 }
207
209}
210
212{
214 return;
215 }
216
218
219 if(is_log_dir_writable_.value_or(false)) {
220#ifdef _WIN32
221 std::string old_path = output_file_path_;
223
224 // flush and close existing log files, since Windows doesn't allow moving open files
225 std::fflush(stderr);
226 std::cerr.flush();
227 if(!std::freopen("NUL", "a", stderr)) {
228 std::cerr << "Failed to close stderr log file: '" << old_path << "'";
229 // stderr is where basically all output goes through, so if that fails then don't attempt anything else
230 // moving just the stdout log would be pointless
231 return;
232 }
233 std::fflush(stdout);
234 std::cout.flush();
235 if(!std::freopen("NUL", "a", stdout)) {
236 std::cerr << "Failed to close stdout log file: '" << old_path << "'";
237 }
238
239 // move the .log and .out.log files
240 // stdout and stderr are set to NUL currently so nowhere to send info on failure
241 if(rename((old_path+lg::log_file_suffix).c_str(), (output_file_path_+lg::log_file_suffix).c_str()) == -1) {
242 return;
243 }
244 rename((old_path+lg::out_log_file_suffix).c_str(), (output_file_path_+lg::out_log_file_suffix).c_str());
245
246 // reopen to log files at new location
247 // stdout and stderr are still NUL if freopen fails, so again nowhere to send info on failure
248 std::fflush(stderr);
249 std::cerr.flush();
250 std::freopen((output_file_path_+lg::log_file_suffix).c_str(), "a", stderr);
251
252 std::fflush(stdout);
253 std::cout.flush();
254 std::freopen((output_file_path_+lg::out_log_file_suffix).c_str(), "a", stdout);
255#else
256 std::string old_path = get_log_file_path();
258
259 // non-Windows can just move the file
260 if(rename(old_path.c_str(), get_log_file_path().c_str()) == -1) {
261 std::cerr << "Failed to rename log file from '" << old_path << "' to '" << output_file_path_ << "'";
262 }
263#endif
264 }
265}
266
268{
270 // if the log directory is not writable, then don't try to do anything.
271 // if the log directory is writable, then setup logging and rotate the logs.
272 // if the optional isn't set, then logging to file has been disabled, so don't try to do anything
273 if(is_log_dir_writable_.value_or(false)) {
274 // get the log file stream and assign cerr+cout to it
277
278 // IMPORTANT: apparently redirecting stderr/stdout will also redirect std::cerr/std::cout, but the reverse is not true
279 // redirecting std::cerr/std::cout will *not* redirect stderr/stdout
280
281 // redirect stderr to file
282 std::fflush(stderr);
283 std::cerr.flush();
284 if(!std::freopen((output_file_path_+lg::log_file_suffix).c_str(), "w", stderr)) {
285 std::cerr << "Failed to redirect stderr to a file!";
286 }
287
288 // redirect stdout to file
289 // separate handling for Windows since dup2() just... doesn't work for GUI apps there apparently
290 // redirect to a separate file on Windows as well, since otherwise two streams independently writing to the same file can cause weirdness
291#ifdef _WIN32
292 std::fflush(stdout);
293 std::cout.flush();
294 if(!std::freopen((output_file_path_+lg::out_log_file_suffix).c_str(), "w", stdout)) {
295 std::cerr << "Failed to redirect stdout to a file!";
296 }
297#else
298 if(dup2(STDERR_FILENO, STDOUT_FILENO) == -1) {
299 std::cerr << "Failed to redirect stdout to a file!";
300 }
301#endif
302
303 // make stdout unbuffered - otherwise some output might be lost
304 // in practice shouldn't make much difference either way, given how little output goes through stdout/std::cout
305 if(setvbuf(stdout, nullptr, _IONBF, 2) == -1) {
306 std::cerr << "Failed to set stdout to be unbuffered";
307 }
308
310 }
311}
312
313utils::optional<bool> log_dir_writable()
314{
316}
317
318std::string get_log_file_path()
319{
321}
322
324 : old_stream_(output_stream_)
325{
326 output_stream_ = &stream;
327}
328
333
334typedef std::map<std::string, severity> domain_map;
337void timestamps(bool t) { timestamp = t; }
339
341{
342 static logger lg("error", severity::LG_ERROR);
343 return lg;
344}
345
347{
348 static logger lg("warning", severity::LG_WARN);
349 return lg;
350}
351
353{
354 static logger lg("info", severity::LG_INFO);
355 return lg;
356}
357
359{
360 static logger lg("debug", severity::LG_DEBUG);
361 return lg;
362}
363
364static log_domain dom("general");
365
367{
368 return dom;
369}
370
372 : domain_(nullptr)
373{
374 // Indirection to prevent initialization depending on link order.
375 if (!domains) domains = new domain_map;
376 domain_ = &*domains->insert(logd(name, severity)).first;
377 domain_->second = severity;
378}
379
380bool set_log_domain_severity(const std::string& name, severity severity)
381{
382 if (name == "all") {
383 for(logd &l : *domains) {
384 l.second = severity;
385 }
386 return true;
387 } else {
388 bool any_matched = false;
389 for (logd &l : *domains) {
390 if (utils::wildcard_string_match(l.first, name)) {
391 l.second = severity;
392 any_matched = true;
393 }
394 }
395 return any_matched;
396 }
397}
398bool set_log_domain_severity(const std::string& name, const logger &lg) {
399 return set_log_domain_severity(name, lg.get_severity());
400}
401
402bool get_log_domain_severity(const std::string& name, severity &severity)
403{
404 domain_map::iterator it = domains->find(name);
405 if (it == domains->end())
406 return false;
407 severity = it->second;
408 return true;
409}
410
411std::string list_log_domains(const std::string& filter)
412{
413 std::ostringstream res;
414 for(logd &l : *domains) {
415 if(l.first.find(filter) != std::string::npos)
416 res << l.first << "\n";
417 }
418 return res.str();
419}
420
424
426 set_strict_severity(lg.get_severity());
427}
428
429static bool strict_threw_ = false;
430
432 return strict_threw_;
433}
434
435void set_log_sanitize(bool sanitize) {
436 log_sanitization = sanitize;
437}
438
439std::string sanitize_log(const std::string& logstr)
440{
441 if(!log_sanitization) {
442 return logstr;
443 }
444
445 std::string str = logstr;
446
447#ifdef _WIN32
448 const char* user_name = getenv("USERNAME");
449#else
450 const char* user_name = getenv("USER");
451#endif
452
453 if(user_name != nullptr) {
454 boost::replace_all(str, std::string("/") + user_name + "/", "/USER/");
455 boost::replace_all(str, std::string("\\") + user_name + "\\", "\\USER\\");
456 }
457
458 return str;
459}
460
462 const log_domain& domain,
463 bool show_names,
464 bool do_indent,
465 bool show_timestamps,
466 bool break_strict,
467 bool auto_newline) const
468{
469 if (severity_ > domain.domain_->second) {
470 return null_ostream;
471 } else {
472 log_in_progress stream = output();
473 if(do_indent) {
474 stream.set_indent(indent);
475 }
476 if (timestamp && show_timestamps) {
477 stream.enable_timestamp();
478 }
479 if (show_names) {
480 stream.set_prefix(formatter() << name_ << ' ' << domain.domain_->first << ": ");
481 }
482 if (!strict_threw_ && severity_ <= strict_level_ && break_strict) {
483 stream | formatter() << "Error (strict mode, strict_level = " << strict_level_ << "): wesnoth reported on channel " << name_ << " " << domain.domain_->first << std::endl;
484 strict_threw_ = true;
485 }
486 stream.set_auto_newline(auto_newline);
487 return stream;
488 }
489}
490
492 : stream_(stream)
493{}
494
496{
497 std::scoped_lock lock(log_mutex);
498 for(int i = 0; i < indent; ++i)
499 stream_ << " ";
500 if(timestamp_) {
501 auto now = std::chrono::system_clock::now();
502 stream_ << chrono::format_local_timestamp(now, "%Y%m%d %H:%M:%S"); // Truncates precision to seconds
504 auto as_seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
505 auto fractional = std::chrono::duration_cast<std::chrono::microseconds>(now - as_seconds);
506 stream_ << "." << std::setw(6) << fractional.count();
507 }
508 stream_ << " ";
509 }
510 stream_ << prefix_ << sanitize_log(message.str());
511 if(auto_newline_) {
512 stream_ << std::endl;
513 }
514}
515
517 indent_ = level;
518}
519
523
524void log_in_progress::set_prefix(const std::string& prefix) {
525 prefix_ = prefix;
526}
527
528void log_in_progress::set_auto_newline(bool auto_newline) {
529 auto_newline_ = auto_newline;
530}
531
532void scope_logger::do_log_entry(const std::string& str) noexcept
533{
534 str_ = str;
535 start_ = std::chrono::steady_clock::now();
536 debug()(domain_, false, true) | formatter() << "{ BEGIN: " << str_;
537 ++indent;
538}
539
541{
542 --indent;
543 auto output = debug()(domain_, false, true);
544 output.set_indent(indent);
545 if(timestamp) output.enable_timestamp();
546 auto now = std::chrono::steady_clock::now();
547 auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(now - start_);
548 output | formatter() << "} END: " << str_ << " (took " << elapsed.count() << "us)"; // FIXME c++20 stream: operator
549}
550
551std::stringstream& log_to_chat()
552{
553 static std::stringstream lg;
554 return lg;
555}
556
557} // end namespace lg
double t
std::ostringstream wrapper.
Definition formatter.hpp:40
logd * domain_
Definition log.hpp:125
log_domain(char const *name, severity severity=severity::LG_WARN)
Definition log.cpp:371
std::string prefix_
Definition log.hpp:195
std::ostream & stream_
Definition log.hpp:192
void set_auto_newline(bool enabled)
Definition log.cpp:528
void set_prefix(const std::string &prefix)
Definition log.cpp:524
void enable_timestamp()
Definition log.cpp:520
void operator|(const formatter &message)
Definition log.cpp:495
void set_indent(int level)
Definition log.cpp:516
log_in_progress(std::ostream &stream)
Definition log.cpp:491
char const * name_
Definition log.hpp:207
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:461
severity severity_
Definition log.hpp:208
std::ostream * old_stream_
The previously set redirection.
Definition log.hpp:117
redirect_output_setter(std::ostream &stream)
Constructor.
Definition log.cpp:323
const log_domain & domain_
Definition log.hpp:241
void do_log_entry(const std::string &str) noexcept
Definition log.cpp:532
std::string str_
Definition log.hpp:242
std::chrono::steady_clock::time_point start_
Definition log.hpp:240
void do_log_exit() noexcept
Definition log.cpp:540
uint32_t get_next_random()
Get a new random number.
Definition mt_rng.cpp:62
Declarations for File-IO.
#define ERR_LS
#define LOG_LS
static std::ostream & output()
Definition log.cpp:104
static bool precise_timestamp
Definition log.cpp:91
static std::string logs_dir_
path to the current logs directory; may change after being initially set if a custom userdata directo...
Definition log.cpp:119
static utils::optional< bool > is_log_dir_writable_
whether the current logs directory is writable
Definition log.cpp:97
static std::string output_file_path_
path to the current log file; does not include the extension
Definition log.cpp:117
static std::ostream null_ostream(new null_streambuf)
static std::mutex log_mutex
Definition log.cpp:92
static int indent
Definition log.cpp:89
static bool log_sanitization
Definition log.cpp:94
static std::ostream * output_stream_
alternative stream to write data to
Definition log.cpp:99
static lg::log_domain log_setup("logsetup")
static bool timestamp
Definition log.cpp:90
Standard logging facilities (interface).
auto format_local_timestamp(const std::chrono::system_clock::time_point &time, std::string_view format="%F %T")
Definition chrono.hpp:72
bool file_exists(const std::string &name)
Returns true if a file or directory with such name already exists.
void get_files_in_dir(const std::string &dir, std::vector< std::string > *files, std::vector< std::string > *dirs=nullptr, name_mode mode=name_mode::FILE_NAME_ONLY, filter_mode filter=filter_mode::NO_FILTER, reorder_mode reorder=reorder_mode::DONT_REORDER, file_tree_checksum *checksum=nullptr)
Get a list of all files and/or directories in a given directory.
bool delete_file(const std::string &filename)
int file_size(const std::string &fname)
Returns the size of a file, or -1 if the file doesn't exist.
void write_file(const std::string &fname, const std::string &data, std::ios_base::openmode mode=std::ios_base::binary)
Throws io_exception if an error occurs.
std::string get_logs_dir()
bool make_directory(const std::string &dirname)
Definition pump.hpp:41
bool get_log_domain_severity(const std::string &name, severity &severity)
Definition log.cpp:402
logger & err()
Definition log.cpp:340
severity
Definition log.hpp:82
std::string list_log_domains(const std::string &filter)
Definition log.cpp:411
log_domain & general()
Definition log.cpp:366
bool broke_strict()
Definition log.cpp:431
logger & debug()
Definition log.cpp:358
const std::string out_log_file_suffix
Definition log.hpp:70
void rotate_logs(const std::string &log_dir)
Check how many log files exist and delete the oldest when there's too many.
Definition log.cpp:135
std::string unique_log_filename()
Generate a unique file name using the current timestamp and a randomly generated number.
Definition log.cpp:166
void set_log_to_file()
Do the initial redirection to a log file if the logs directory is writable.
Definition log.cpp:267
static log_domain dom("general")
void set_log_sanitize(bool sanitize)
toggle log sanitization
Definition log.cpp:435
utils::optional< bool > log_dir_writable()
Returns the result set by check_log_dir_writable().
Definition log.cpp:313
void move_log_file()
Move the log file to another directory.
Definition log.cpp:211
logger & warn()
Definition log.cpp:346
void timestamps(bool t)
Definition log.cpp:337
std::string sanitize_log(const std::string &logstr)
Definition log.cpp:439
static severity strict_level_
Definition log.cpp:336
const unsigned max_logs
Definition log.hpp:75
void check_log_dir_writable()
Checks that a dummy file can be written to and deleted from the logs directory.
Definition log.cpp:179
std::stringstream & log_to_chat()
Use this to show WML errors in the ingame chat.
Definition log.cpp:551
const std::string log_file_prefix
Definition log.hpp:67
std::map< std::string, severity > domain_map
Definition log.cpp:334
static domain_map * domains
Definition log.cpp:335
std::pair< const std::string, severity > logd
Definition log.hpp:122
static bool strict_threw_
Definition log.cpp:429
bool is_not_log_file(const std::string &fn)
Use the defined prefix and suffix to determine if a filename is a log file.
Definition log.cpp:129
void precise_timestamps(bool pt)
Definition log.cpp:338
logger & info()
Definition log.cpp:352
bool set_log_domain_severity(const std::string &name, severity severity)
Definition log.cpp:380
void set_strict_severity(severity severity)
Definition log.cpp:421
std::string get_log_file_path()
Definition log.cpp:318
const std::string log_file_suffix
Definition log.hpp:68
std::ostringstream & operator<<(std::ostringstream &oss, const lg::severity severity)
Definition log.cpp:123
bool wildcard_string_match(std::string_view str, std::string_view pat) noexcept
Performs pattern matching with wildcards.
void erase_if(Container &container, const Predicate &predicate)
Convenience wrapper for using std::remove_if on a container.
Definition general.hpp:108
An exception object used when an IO error occurs.
static map_location::direction n
static map_location::direction s
#define i
#define c