Debian Codegraph @

contrib/epee/src/mlog.cpp

raw symbols SCIP
1 // Copyright (c) 2006-2013, Andrey N. Sabelnikov, www.sabelnikov.net
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are met:
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above copyright
9 // notice, this list of conditions and the following disclaimer in the
10 // documentation and/or other materials provided with the distribution.
11 // * Neither the name of the Andrey N. Sabelnikov nor the
12 // names of its contributors may be used to endorse or promote products
13 // derived from this software without specific prior written permission.
14 //
15 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16 // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY
19 // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22 // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 //
26
27
28 #ifndef _MLOG_H_
29 #define _MLOG_H_
30
31 #ifdef _WIN32
32 #include <windows.h>
33 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
34 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
35 #endif
36 #endif
37
38 #include <time.h>
39 #include <atomic>
40 #include <boost/filesystem.hpp>
41 #include <boost/algorithm/string.hpp>
42 #include "string_tools.h"
43 #include "time_helper.h"
44 #include "misc_log_ex.h"
45
46 #undef MONERO_DEFAULT_LOG_CATEGORY
47 #define MONERO_DEFAULT_LOG_CATEGORY "logging"
48
49 #define MLOG_BASE_FORMAT "%datetime{%Y-%M-%d %H:%m:%s.%g}\t%thread\t%level\t%logger\t%loc\t%msg"
50
51 #define MLOG_LOG(x) CINFO(el::base::Writer,el::base::DispatchAction::FileOnlyLog,MONERO_DEFAULT_LOG_CATEGORY) << x
52
53 using namespace epee;
54
55 static std::string generate_log_filename(const char *base)
56 {
57 std::string filename(base);
58 static unsigned int fallback_counter = 0;
59 char tmp[200];
60 struct tm tm;
61 time_t now = time(NULL);
62 if (!epee::misc_utils::get_gmt_time(now, tm))
63 snprintf(tmp, sizeof(tmp), "part-%u", ++fallback_counter);
64 else
65 strftime(tmp, sizeof(tmp), "%Y-%m-%d-%H-%M-%S", &tm);
66 tmp[sizeof(tmp) - 1] = 0;
67 filename += "-";
68 filename += tmp;
69 return filename;
70 }
71
72 std::string mlog_get_default_log_path(const char *default_filename)
73 {
74 std::string process_name = epee::string_tools::get_current_module_name();
75 std::string default_log_folder = epee::string_tools::get_current_module_folder();
76 std::string default_log_file = process_name;
77 std::string::size_type a = default_log_file.rfind('.');
78 if ( a != std::string::npos )
79 default_log_file.erase( a, default_log_file.size());
80 if ( ! default_log_file.empty() )
81 default_log_file += ".log";
82 else
83 default_log_file = default_filename;
84
85 return (boost::filesystem::path(default_log_folder) / boost::filesystem::path(default_log_file)).string();
86 }
87
88 static void mlog_set_common_prefix()
89 {
90 static const char * const expected_filename = "contrib/epee/src/mlog.cpp";
91 const char *path = __FILE__, *expected_ptr = strstr(path, expected_filename);
92 if (!expected_ptr)
93 return;
94 el::Loggers::setFilenameCommonPrefix(std::string(path, expected_ptr - path));
95 }
96
97 static const char *get_default_categories(int level)
98 {
99 const char *categories = "";
100 switch (level)
101 {
102 case 0:
103 categories = "*:WARNING,net:FATAL,net.http:FATAL,net.ssl:FATAL,net.p2p:FATAL,net.cn:FATAL,daemon.rpc:FATAL,global:INFO,verify:FATAL,serialization:FATAL,daemon.rpc.payment:ERROR,stacktrace:INFO,logging:INFO,msgwriter:INFO";
104 break;
105 case 1:
106 categories = "*:INFO,global:INFO,stacktrace:INFO,logging:INFO,msgwriter:INFO,perf.*:DEBUG";
107 break;
108 case 2:
109 categories = "*:DEBUG";
110 break;
111 case 3:
112 categories = "*:TRACE,*.dump:DEBUG";
113 break;
114 case 4:
115 categories = "*:TRACE";
116 break;
117 default:
118 break;
119 }
120 return categories;
121 }
122
123 #ifdef WIN32
124 bool EnableVTMode()
125 {
126 // Set output mode to handle virtual terminal sequences
127 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
128 if (hOut == INVALID_HANDLE_VALUE)
129 {
130 return false;
131 }
132
133 DWORD dwMode = 0;
134 if (!GetConsoleMode(hOut, &dwMode))
135 {
136 return false;
137 }
138
139 dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
140 if (!SetConsoleMode(hOut, dwMode))
141 {
142 return false;
143 }
144 return true;
145 }
146 #endif
147
148 void mlog_configure(const std::string &filename_base, bool console, const std::size_t max_log_file_size, const std::size_t max_log_files)
149 {
150 el::Configurations c;
151 c.setGlobally(el::ConfigurationType::Filename, filename_base);
152 c.setGlobally(el::ConfigurationType::ToFile, "true");
153 const char *log_format = getenv("MONERO_LOG_FORMAT");
154 if (!log_format)
155 log_format = MLOG_BASE_FORMAT;
156 c.setGlobally(el::ConfigurationType::Format, log_format);
157 c.setGlobally(el::ConfigurationType::ToStandardOutput, console ? "true" : "false");
158 c.setGlobally(el::ConfigurationType::MaxLogFileSize, std::to_string(max_log_file_size));
159 el::Loggers::setDefaultConfigurations(c, true);
160
161 el::Loggers::addFlag(el::LoggingFlag::HierarchicalLogging);
162 el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically);
163 el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog);
164 el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput);
165 el::Loggers::addFlag(el::LoggingFlag::StrictLogFileSizeCheck);
166 el::Helpers::installPreRollOutCallback([filename_base, max_log_files](const char *name, size_t){
167 std::string rname = generate_log_filename(filename_base.c_str());
168 int ret = rename(name, rname.c_str());
169 if (ret < 0)
170 {
171 // can't log a failure, but don't do the file removal below
172 return;
173 }
174 if (max_log_files != 0)
175 {
176 std::vector<boost::filesystem::path> found_files;
177 const boost::filesystem::directory_iterator end_itr;
178 const boost::filesystem::path filename_base_path(filename_base);
179 const std::string filename_base_name = filename_base_path.filename().string();
180 const boost::filesystem::path parent_path = filename_base_path.has_parent_path() ? filename_base_path.parent_path() : ".";
181 for (boost::filesystem::directory_iterator iter(parent_path); iter != end_itr; ++iter)
182 {
183 const std::string filename = iter->path().filename().string();
184 if (filename.size() >= filename_base_name.size() && std::memcmp(filename.data(), filename_base_name.data(), filename_base_name.size()) == 0)
185 {
186 found_files.push_back(iter->path());
187 }
188 }
189 if (found_files.size() >= max_log_files)
190 {
191 std::sort(found_files.begin(), found_files.end(), [](const boost::filesystem::path &a, const boost::filesystem::path &b) {
192 boost::system::error_code ec;
193 std::time_t ta = boost::filesystem::last_write_time(boost::filesystem::path(a), ec);
194 if (ec)
195 {
196 MERROR("Failed to get timestamp from " << a << ": " << ec);
197 ta = std::time(nullptr);
198 }
199 std::time_t tb = boost::filesystem::last_write_time(boost::filesystem::path(b), ec);
200 if (ec)
201 {
202 MERROR("Failed to get timestamp from " << b << ": " << ec);
203 tb = std::time(nullptr);
204 }
205 static_assert(std::is_integral<time_t>(), "bad time_t");
206 return ta < tb;
207 });
208 for (size_t i = 0; i <= found_files.size() - max_log_files; ++i)
209 {
210 try
211 {
212 boost::system::error_code ec;
213 boost::filesystem::remove(found_files[i], ec);
214 if (ec)
215 {
216 MERROR("Failed to remove " << found_files[i] << ": " << ec);
217 }
218 }
219 catch (const std::exception &e)
220 {
221 MERROR("Failed to remove " << found_files[i] << ": " << e.what());
222 }
223 }
224 }
225 }
226 });
227 mlog_set_common_prefix();
228 const char *monero_log = getenv("MONERO_LOGS");
229 if (!monero_log)
230 {
231 monero_log = get_default_categories(0);
232 }
233 mlog_set_log(monero_log);
234 #ifdef WIN32
235 EnableVTMode();
236 #endif
237 }
238
239 void mlog_set_categories(const char *categories)
240 {
241 std::string new_categories;
242 if (*categories)
243 {
244 if (*categories == '+')
245 {
246 ++categories;
247 new_categories = mlog_get_categories();
248 if (*categories)
249 {
250 if (!new_categories.empty())
251 new_categories += ",";
252 new_categories += categories;
253 }
254 }
255 else if (*categories == '-')
256 {
257 ++categories;
258 new_categories = mlog_get_categories();
259 std::vector<std::string> single_categories;
260 boost::split(single_categories, categories, boost::is_any_of(","), boost::token_compress_on);
261 for (const std::string &s: single_categories)
262 {
263 size_t pos = new_categories.find(s);
264 if (pos != std::string::npos)
265 new_categories = new_categories.erase(pos, s.size());
266 }
267 }
268 else
269 {
270 new_categories = categories;
271 }
272 }
273 el::Loggers::setCategories(new_categories.c_str(), true);
274 MLOG_LOG("New log categories: " << el::Loggers::getCategories());
275 }
276
277 std::string mlog_get_categories()
278 {
279 return el::Loggers::getCategories();
280 }
281
282 // maps epee style log level to new logging system
283 void mlog_set_log_level(int level)
284 {
285 const char *categories = get_default_categories(level);
286 mlog_set_categories(categories);
287 }
288
289 void mlog_set_log(const char *log)
290 {
291 long level;
292 char *ptr = NULL;
293
294 if (!*log)
295 {
296 mlog_set_categories(log);
297 return;
298 }
299 level = strtol(log, &ptr, 10);
300 if (ptr && *ptr)
301 {
302 // we can have a default level, eg, 2,foo:ERROR
303 if (*ptr == ',') {
304 std::string new_categories = std::string(get_default_categories(level)) + ptr;
305 mlog_set_categories(new_categories.c_str());
306 }
307 else {
308 mlog_set_categories(log);
309 }
310 }
311 else if (level >= 0 && level <= 4)
312 {
313 mlog_set_log_level(level);
314 }
315 else
316 {
317 MERROR("Invalid numerical log level: " << log);
318 }
319 }
320
321 namespace epee
322 {
323
324 bool is_stdout_a_tty()
325 {
326 static std::atomic<bool> initialized(false);
327 static std::atomic<bool> is_a_tty(false);
328
329 if (!initialized.load(std::memory_order_acquire))
330 {
331 #if defined(WIN32)
332 is_a_tty.store(0 != _isatty(_fileno(stdout)), std::memory_order_relaxed);
333 #else
334 is_a_tty.store(0 != isatty(fileno(stdout)), std::memory_order_relaxed);
335 #endif
336 initialized.store(true, std::memory_order_release);
337 }
338
339 return is_a_tty.load(std::memory_order_relaxed);
340 }
341
342 static bool is_nocolor()
343 {
344 static const char *no_color_var = getenv("NO_COLOR");
345 static const bool no_color = no_color_var && *no_color_var; // apparently, NO_COLOR=0 means no color too (as per no-color.org)
346 return no_color;
347 }
348
349 void set_console_color(int color, bool bright)
350 {
351 if (!is_stdout_a_tty())
352 return;
353
354 if (is_nocolor())
355 return;
356
357 switch(color)
358 {
359 case console_color_default:
360 {
361 #ifdef WIN32
362 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
363 SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE| (bright ? FOREGROUND_INTENSITY:0));
364 #else
365 if(bright)
366 std::cout << "\033[1;37m";
367 else
368 std::cout << "\033[0m";
369 #endif
370 }
371 break;
372 case console_color_white:
373 {
374 #ifdef WIN32
375 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
376 SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | (bright ? FOREGROUND_INTENSITY:0));
377 #else
378 if(bright)
379 std::cout << "\033[1;37m";
380 else
381 std::cout << "\033[0;37m";
382 #endif
383 }
384 break;
385 case console_color_red:
386 {
387 #ifdef WIN32
388 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
389 SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | (bright ? FOREGROUND_INTENSITY:0));
390 #else
391 if(bright)
392 std::cout << "\033[1;31m";
393 else
394 std::cout << "\033[0;31m";
395 #endif
396 }
397 break;
398 case console_color_green:
399 {
400 #ifdef WIN32
401 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
402 SetConsoleTextAttribute(h_stdout, FOREGROUND_GREEN | (bright ? FOREGROUND_INTENSITY:0));
403 #else
404 if(bright)
405 std::cout << "\033[1;32m";
406 else
407 std::cout << "\033[0;32m";
408 #endif
409 }
410 break;
411
412 case console_color_blue:
413 {
414 #ifdef WIN32
415 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
416 SetConsoleTextAttribute(h_stdout, FOREGROUND_BLUE | FOREGROUND_INTENSITY);//(bright ? FOREGROUND_INTENSITY:0));
417 #else
418 if(bright)
419 std::cout << "\033[1;34m";
420 else
421 std::cout << "\033[0;34m";
422 #endif
423 }
424 break;
425
426 case console_color_cyan:
427 {
428 #ifdef WIN32
429 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
430 SetConsoleTextAttribute(h_stdout, FOREGROUND_GREEN | FOREGROUND_BLUE | (bright ? FOREGROUND_INTENSITY:0));
431 #else
432 if(bright)
433 std::cout << "\033[1;36m";
434 else
435 std::cout << "\033[0;36m";
436 #endif
437 }
438 break;
439
440 case console_color_magenta:
441 {
442 #ifdef WIN32
443 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
444 SetConsoleTextAttribute(h_stdout, FOREGROUND_BLUE | FOREGROUND_RED | (bright ? FOREGROUND_INTENSITY:0));
445 #else
446 if(bright)
447 std::cout << "\033[1;35m";
448 else
449 std::cout << "\033[0;35m";
450 #endif
451 }
452 break;
453
454 case console_color_yellow:
455 {
456 #ifdef WIN32
457 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
458 SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | (bright ? FOREGROUND_INTENSITY:0));
459 #else
460 if(bright)
461 std::cout << "\033[1;33m";
462 else
463 std::cout << "\033[0;33m";
464 #endif
465 }
466 break;
467
468 }
469 }
470
471 void reset_console_color() {
472 if (!is_stdout_a_tty())
473 return;
474
475 if (is_nocolor())
476 return;
477
478 #ifdef WIN32
479 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
480 SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
481 #else
482 std::cout << "\033[0m";
483 std::cout.flush();
484 #endif
485 }
486
487 }
488
489 static bool mlog(el::Level level, const char *category, const char *format, va_list ap) noexcept
490 {
491 int size = 0;
492 char *p = NULL;
493 va_list apc;
494 bool ret = true;
495
496 /* Determine required size */
497 va_copy(apc, ap);
498 size = vsnprintf(p, size, format, apc);
499 va_end(apc);
500 if (size < 0)
501 return false;
502
503 size++; /* For '\0' */
504 p = (char*)malloc(size);
505 if (p == NULL)
506 return false;
507
508 size = vsnprintf(p, size, format, ap);
509 if (size < 0)
510 {
511 free(p);
512 return false;
513 }
514
515 try
516 {
517 MCLOG(level, category, el::Color::Default, p);
518 }
519 catch(...)
520 {
521 ret = false;
522 }
523 free(p);
524
525 return ret;
526 }
527
528 #define DEFLOG(fun,lev) \
529 bool m##fun(const char *category, const char *fmt, ...) { va_list ap; va_start(ap, fmt); bool ret = mlog(el::Level::lev, category, fmt, ap); va_end(ap); return ret; }
530
531 DEFLOG(error, Error)
532 DEFLOG(warning, Warning)
533 DEFLOG(info, Info)
534 DEFLOG(debug, Debug)
535 DEFLOG(trace, Trace)
536
537 #undef DEFLOG
538
539 #endif //_MLOG_H_