Debian Codegraph @

monero/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.*:WARNING";
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
229 #ifdef WIN32
230 EnableVTMode();
231 #endif
232 }
233
234 void mlog_set_categories(const char *categories)
235 {
236 std::string new_categories;
237 if (*categories)
238 {
239 if (*categories == '+')
240 {
241 ++categories;
242 new_categories = mlog_get_categories();
243 if (*categories)
244 {
245 if (!new_categories.empty())
246 new_categories += ",";
247 new_categories += categories;
248 }
249 }
250 else if (*categories == '-')
251 {
252 ++categories;
253 new_categories = mlog_get_categories();
254 std::vector<std::string> single_categories;
255 boost::split(single_categories, categories, boost::is_any_of(","), boost::token_compress_on);
256 for (const std::string &s: single_categories)
257 {
258 size_t pos = new_categories.find(s);
259 if (pos != std::string::npos)
260 new_categories = new_categories.erase(pos, s.size());
261 }
262 }
263 else
264 {
265 new_categories = categories;
266 }
267 }
268 el::Loggers::setCategories(new_categories.c_str(), true);
269 MLOG_LOG("New log categories: " << el::Loggers::getCategories());
270 }
271
272 std::string mlog_get_categories()
273 {
274 return el::Loggers::getCategories();
275 }
276
277 // maps epee style log level to new logging system
278 void mlog_set_log_level(int level)
279 {
280 const char *categories = get_default_categories(level);
281 mlog_set_categories(categories);
282 }
283
284 void mlog_set_log(const char *log)
285 {
286 long level;
287 char *ptr = NULL;
288
289 if (!*log)
290 {
291 mlog_set_categories(log);
292 return;
293 }
294 level = strtol(log, &ptr, 10);
295 if (ptr && *ptr)
296 {
297 // we can have a default level, eg, 2,foo:ERROR
298 if (*ptr == ',') {
299 std::string new_categories = std::string(get_default_categories(level)) + ptr;
300 mlog_set_categories(new_categories.c_str());
301 }
302 else {
303 mlog_set_categories(log);
304 }
305 }
306 else if (level >= 0 && level <= 4)
307 {
308 mlog_set_log_level(level);
309 }
310 else
311 {
312 MERROR("Invalid numerical log level: " << log);
313 }
314 }
315
316 namespace epee
317 {
318
319 bool is_stdout_a_tty()
320 {
321 static std::atomic<bool> initialized(false);
322 static std::atomic<bool> is_a_tty(false);
323
324 if (!initialized.load(std::memory_order_acquire))
325 {
326 #if defined(WIN32)
327 is_a_tty.store(0 != _isatty(_fileno(stdout)), std::memory_order_relaxed);
328 #else
329 is_a_tty.store(0 != isatty(fileno(stdout)), std::memory_order_relaxed);
330 #endif
331 initialized.store(true, std::memory_order_release);
332 }
333
334 return is_a_tty.load(std::memory_order_relaxed);
335 }
336
337 static bool is_nocolor()
338 {
339 static const char *no_color_var = getenv("NO_COLOR");
340 static const bool no_color = no_color_var && *no_color_var; // apparently, NO_COLOR=0 means no color too (as per no-color.org)
341 return no_color;
342 }
343
344 void set_console_color(int color, bool bright)
345 {
346 if (!is_stdout_a_tty())
347 return;
348
349 if (is_nocolor())
350 return;
351
352 switch(color)
353 {
354 case console_color_default:
355 {
356 #ifdef WIN32
357 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
358 SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE| (bright ? FOREGROUND_INTENSITY:0));
359 #else
360 if(bright)
361 std::cout << "\033[1;37m";
362 else
363 std::cout << "\033[0m";
364 #endif
365 }
366 break;
367 case console_color_white:
368 {
369 #ifdef WIN32
370 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
371 SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | (bright ? FOREGROUND_INTENSITY:0));
372 #else
373 if(bright)
374 std::cout << "\033[1;37m";
375 else
376 std::cout << "\033[0;37m";
377 #endif
378 }
379 break;
380 case console_color_red:
381 {
382 #ifdef WIN32
383 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
384 SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | (bright ? FOREGROUND_INTENSITY:0));
385 #else
386 if(bright)
387 std::cout << "\033[1;31m";
388 else
389 std::cout << "\033[0;31m";
390 #endif
391 }
392 break;
393 case console_color_green:
394 {
395 #ifdef WIN32
396 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
397 SetConsoleTextAttribute(h_stdout, FOREGROUND_GREEN | (bright ? FOREGROUND_INTENSITY:0));
398 #else
399 if(bright)
400 std::cout << "\033[1;32m";
401 else
402 std::cout << "\033[0;32m";
403 #endif
404 }
405 break;
406
407 case console_color_blue:
408 {
409 #ifdef WIN32
410 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
411 SetConsoleTextAttribute(h_stdout, FOREGROUND_BLUE | FOREGROUND_INTENSITY);//(bright ? FOREGROUND_INTENSITY:0));
412 #else
413 if(bright)
414 std::cout << "\033[1;34m";
415 else
416 std::cout << "\033[0;34m";
417 #endif
418 }
419 break;
420
421 case console_color_cyan:
422 {
423 #ifdef WIN32
424 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
425 SetConsoleTextAttribute(h_stdout, FOREGROUND_GREEN | FOREGROUND_BLUE | (bright ? FOREGROUND_INTENSITY:0));
426 #else
427 if(bright)
428 std::cout << "\033[1;36m";
429 else
430 std::cout << "\033[0;36m";
431 #endif
432 }
433 break;
434
435 case console_color_magenta:
436 {
437 #ifdef WIN32
438 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
439 SetConsoleTextAttribute(h_stdout, FOREGROUND_BLUE | FOREGROUND_RED | (bright ? FOREGROUND_INTENSITY:0));
440 #else
441 if(bright)
442 std::cout << "\033[1;35m";
443 else
444 std::cout << "\033[0;35m";
445 #endif
446 }
447 break;
448
449 case console_color_yellow:
450 {
451 #ifdef WIN32
452 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
453 SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | (bright ? FOREGROUND_INTENSITY:0));
454 #else
455 if(bright)
456 std::cout << "\033[1;33m";
457 else
458 std::cout << "\033[0;33m";
459 #endif
460 }
461 break;
462
463 }
464 }
465
466 void reset_console_color() {
467 if (!is_stdout_a_tty())
468 return;
469
470 if (is_nocolor())
471 return;
472
473 #ifdef WIN32
474 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
475 SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
476 #else
477 std::cout << "\033[0m";
478 std::cout.flush();
479 #endif
480 }
481
482 }
483
484 static bool mlog(el::Level level, const char *category, const char *format, va_list ap) noexcept
485 {
486 int size = 0;
487 char *p = NULL;
488 va_list apc;
489 bool ret = true;
490
491 /* Determine required size */
492 va_copy(apc, ap);
493 size = vsnprintf(p, size, format, apc);
494 va_end(apc);
495 if (size < 0)
496 return false;
497
498 size++; /* For '\0' */
499 p = (char*)malloc(size);
500 if (p == NULL)
501 return false;
502
503 size = vsnprintf(p, size, format, ap);
504 if (size < 0)
505 {
506 free(p);
507 return false;
508 }
509
510 try
511 {
512 MCLOG(level, category, el::Color::Default, p);
513 }
514 catch(...)
515 {
516 ret = false;
517 }
518 free(p);
519
520 return ret;
521 }
522
523 #define DEFLOG(fun,lev) \
524 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; }
525
526 DEFLOG(error, Error)
527 DEFLOG(warning, Warning)
528 DEFLOG(info, Info)
529 DEFLOG(debug, Debug)
530 DEFLOG(trace, Trace)
531
532 #undef DEFLOG
533
534 #endif //_MLOG_H_