1 /* log - a generic logging facility in the spirit of log4j */
3 /* Copyright (c) 2004-2021. The SimGrid Team. All rights reserved. */
5 /* This program is free software; you can redistribute it and/or modify it
6 * under the terms of the license (GNU LGPL) which comes with this package. */
8 #include "src/xbt/log_private.hpp"
9 #include "xbt/asserts.h"
10 #include "xbt/string.hpp"
11 #include "xbt/xbt_modinter.h"
15 #include <boost/tokenizer.hpp>
20 int xbt_log_no_loc = 0; /* if set to true (with --log=no_loc), file localization will be omitted (for tesh tests) */
21 static std::recursive_mutex* log_cat_init_mutex = nullptr;
23 xbt_log_appender_t xbt_log_default_appender = nullptr; /* set in log_init */
24 xbt_log_layout_t xbt_log_default_layout = nullptr; /* set in log_init */
26 struct xbt_log_setting_t {
29 e_xbt_log_priority_t thresh = xbt_log_priority_uninitialized;
31 xbt_log_appender_t appender = nullptr;
34 // This function is here to avoid static initialization order fiasco
35 static auto& xbt_log_settings()
37 static std::vector<xbt_log_setting_t> value;
41 constexpr std::array<const char*, xbt_log_priority_infinite> xbt_log_priority_names{
42 {"NONE", "TRACE", "DEBUG", "VERBOSE", "INFO", "WARNING", "ERROR", "CRITICAL"}};
44 s_xbt_log_category_t _XBT_LOGV(XBT_LOG_ROOT_CAT) = {
46 nullptr /* firstChild */,
47 nullptr /* nextSibling */,
49 "The common ancestor for all categories",
51 xbt_log_priority_uninitialized /* threshold */,
52 0 /* isThreshInherited */,
53 nullptr /* appender */,
58 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(log, xbt, "Loggings from the logging mechanism itself");
60 /* create the default appender and install it in the root category,
61 which were already created (damnit. Too slow little beetle) */
62 void xbt_log_preinit(void)
64 xbt_log_default_appender = xbt_log_appender_stream(stderr);
65 xbt_log_default_layout = xbt_log_layout_simple_new(nullptr);
66 _XBT_LOGV(XBT_LOG_ROOT_CAT).appender = xbt_log_default_appender;
67 _XBT_LOGV(XBT_LOG_ROOT_CAT).layout = xbt_log_default_layout;
68 log_cat_init_mutex = new std::recursive_mutex();
71 static void xbt_log_help();
72 static void xbt_log_help_categories();
74 void xbt_log_init(int *argc, char **argv)
76 unsigned help_requested = 0; /* 1: logs; 2: categories */
78 int parse_args = 1; // Stop parsing the parameters once we found '--'
80 xbt_log_control_set("xbt_help.app:stdout xbt_help.threshold:VERBOSE xbt_help.fmt:%m%n");
82 /* Set logs and init log submodule */
83 for (int i = 1; i < *argc; i++) {
84 if (strcmp("--", argv[i]) == 0) {
86 argv[j++] = argv[i]; // Keep the '--' for sg_config
87 } else if (parse_args && strncmp(argv[i], "--log=", strlen("--log=")) == 0) {
88 char* opt = strchr(argv[i], '=');
90 xbt_log_control_set(opt);
91 XBT_DEBUG("Did apply '%s' as log setting", opt);
92 } else if (parse_args && strcmp(argv[i], "--help-logs") == 0) {
94 } else if (parse_args && strcmp(argv[i], "--help-log-categories") == 0) {
105 if (help_requested) {
106 if (help_requested & 1)
108 if (help_requested & 2)
109 xbt_log_help_categories();
114 static void log_cat_exit(const s_xbt_log_category_t* cat)
117 if (cat->appender->free_)
118 cat->appender->free_(cat->appender);
119 xbt_free(cat->appender);
122 if (cat->layout->free_)
123 cat->layout->free_(cat->layout);
124 xbt_free(cat->layout);
127 for (auto const* child = cat->firstChild; child != nullptr; child = child->nextSibling)
131 void xbt_log_postexit(void)
133 XBT_VERB("Exiting log");
134 delete log_cat_init_mutex;
135 log_cat_exit(&_XBT_LOGV(XBT_LOG_ROOT_CAT));
138 /* Size of the static string in which we build the log string */
139 static constexpr size_t XBT_LOG_STATIC_BUFFER_SIZE = 2048;
140 /* Minimum size of the dynamic string in which we build the log string
141 (should be greater than XBT_LOG_STATIC_BUFFER_SIZE) */
142 static constexpr size_t XBT_LOG_DYNAMIC_BUFFER_SIZE = 4096;
144 void _xbt_log_event_log(xbt_log_event_t ev, const char *fmt, ...)
146 const xbt_log_category_s* cat = ev->cat;
148 xbt_assert(ev->priority >= 0, "Negative logging priority naturally forbidden");
149 xbt_assert(static_cast<size_t>(ev->priority) < xbt_log_priority_names.size(),
150 "Priority %d is greater than the biggest allowed value", ev->priority);
153 const s_xbt_log_appender_t* appender = cat->appender;
155 if (appender != nullptr) {
156 xbt_assert(cat->layout, "No valid layout for the appender of category %s", cat->name);
158 /* First, try with a static buffer */
160 std::array<char, XBT_LOG_STATIC_BUFFER_SIZE> buff;
161 ev->buffer = buff.data();
162 ev->buffer_size = buff.size();
163 va_start(ev->ap, fmt);
164 done = cat->layout->do_layout(cat->layout, ev, fmt);
166 ev->buffer = nullptr; // Calm down, static analyzers, this pointer to local array won't leak out of the scope.
168 appender->do_append(appender, buff.data());
170 /* The static buffer was too small, use a dynamically expanded one */
171 ev->buffer_size = XBT_LOG_DYNAMIC_BUFFER_SIZE;
172 ev->buffer = static_cast<char*>(xbt_malloc(ev->buffer_size));
174 va_start(ev->ap, fmt);
175 done = cat->layout->do_layout(cat->layout, ev, fmt);
179 ev->buffer_size *= 2;
180 ev->buffer = static_cast<char*>(xbt_realloc(ev->buffer, ev->buffer_size));
182 appender->do_append(appender, ev->buffer);
183 xbt_free(ev->buffer);
187 if (!cat->additivity)
195 * The standard logging macros use _XBT_LOG_ISENABLED, which calls _xbt_log_cat_init(). Thus, if we want to avoid an
196 * infinite recursion, we can not use the standard logging macros in _xbt_log_cat_init(), and in all functions called
199 * To circumvent the problem, we define the macro DISABLE_XBT_LOG_CAT_INIT() to hide the real _xbt_log_cat_init(). The
200 * macro has to be called at the beginning of the affected functions.
202 static int fake_xbt_log_cat_init(xbt_log_category_t, e_xbt_log_priority_t)
206 #define DISABLE_XBT_LOG_CAT_INIT() \
207 int (*_xbt_log_cat_init)(xbt_log_category_t, e_xbt_log_priority_t) XBT_ATTRIB_UNUSED = fake_xbt_log_cat_init
209 static void _xbt_log_cat_apply_set(xbt_log_category_t category, const xbt_log_setting_t& setting)
211 DISABLE_XBT_LOG_CAT_INIT();
212 if (setting.thresh != xbt_log_priority_uninitialized) {
213 xbt_log_threshold_set(category, setting.thresh);
215 XBT_DEBUG("Apply settings for category '%s': set threshold to %s (=%d)",
216 category->name, xbt_log_priority_names[category->threshold], category->threshold);
219 if (not setting.fmt.empty()) {
220 xbt_log_layout_set(category, xbt_log_layout_format_new(setting.fmt.c_str()));
222 XBT_DEBUG("Apply settings for category '%s': set format to %s", category->name, setting.fmt.c_str());
225 if (setting.additivity != -1) {
226 xbt_log_additivity_set(category, setting.additivity);
228 XBT_DEBUG("Apply settings for category '%s': set additivity to %s", category->name,
229 (setting.additivity ? "on" : "off"));
231 if (setting.appender) {
232 xbt_log_appender_set(category, setting.appender);
233 if (!category->layout)
234 xbt_log_layout_set(category, xbt_log_layout_simple_new(nullptr));
235 category->additivity = 0;
236 XBT_DEBUG("Set %p as appender of category '%s'", setting.appender, category->name);
241 * This gets called the first time a category is referenced and performs the initialization.
242 * Also resets threshold to inherited!
244 int _xbt_log_cat_init(xbt_log_category_t category, e_xbt_log_priority_t priority)
246 DISABLE_XBT_LOG_CAT_INIT();
247 if (category->initialized)
248 return priority >= category->threshold;
250 if (log_cat_init_mutex != nullptr)
251 log_cat_init_mutex->lock();
253 XBT_DEBUG("Initializing category '%s' (firstChild=%s, nextSibling=%s)", category->name,
254 (category->firstChild ? category->firstChild->name : "none"),
255 (category->nextSibling ? category->nextSibling->name : "none"));
257 if (category == &_XBT_LOGV(XBT_LOG_ROOT_CAT)) {
258 category->threshold = xbt_log_priority_info;
259 category->appender = xbt_log_default_appender;
260 category->layout = xbt_log_default_layout;
262 if (!category->parent)
263 category->parent = &_XBT_LOGV(XBT_LOG_ROOT_CAT);
265 XBT_DEBUG("Set %s (%s) as father of %s ", category->parent->name,
266 (category->parent->initialized ? xbt_log_priority_names[category->parent->threshold] : "uninited"),
268 xbt_log_parent_set(category, category->parent);
270 if (XBT_LOG_ISENABLED(log, xbt_log_priority_debug)) {
272 const xbt_log_category_s* cpp = category->parent->firstChild;
274 res += std::string(" ") + cpp->name;
275 cpp = cpp->nextSibling;
278 XBT_DEBUG("Children of %s:%s; nextSibling: %s", category->parent->name, res.c_str(),
279 (category->parent->nextSibling ? category->parent->nextSibling->name : "none"));
283 /* Apply the control */
284 auto iset = std::find_if(begin(xbt_log_settings()), end(xbt_log_settings()),
285 [category](const xbt_log_setting_t& s) { return s.catname == category->name; });
286 if (iset != xbt_log_settings().end()) {
287 _xbt_log_cat_apply_set(category, *iset);
288 xbt_log_settings().erase(iset);
290 XBT_DEBUG("Category '%s': inherited threshold = %s (=%d)", category->name,
291 xbt_log_priority_names[category->threshold], category->threshold);
294 category->initialized = 1;
295 if (log_cat_init_mutex != nullptr)
296 log_cat_init_mutex->unlock();
297 return priority >= category->threshold;
300 void xbt_log_parent_set(xbt_log_category_t cat, xbt_log_category_t parent)
302 xbt_assert(cat, "NULL category to be given a parent");
303 xbt_assert(parent, "The parent category of %s is NULL", cat->name);
305 /* if the category is initialized, unlink from current parent */
306 if (cat->initialized) {
307 xbt_log_category_t *cpp = &cat->parent->firstChild;
309 while (*cpp != cat && *cpp != nullptr) {
310 cpp = &(*cpp)->nextSibling;
313 xbt_assert(*cpp == cat);
314 *cpp = cat->nextSibling;
317 cat->parent = parent;
318 cat->nextSibling = parent->firstChild;
320 parent->firstChild = cat;
322 if (!parent->initialized)
323 _xbt_log_cat_init(parent, xbt_log_priority_uninitialized /* ignored */ );
325 cat->threshold = parent->threshold;
327 cat->isThreshInherited = 1;
330 static void _set_inherited_thresholds(const s_xbt_log_category_t* cat)
332 xbt_log_category_t child = cat->firstChild;
334 for (; child != nullptr; child = child->nextSibling) {
335 if (child->isThreshInherited) {
336 if (cat != &_XBT_LOGV(log))
337 XBT_VERB("Set category threshold of %s to %s (=%d)",
338 child->name, xbt_log_priority_names[cat->threshold], cat->threshold);
339 child->threshold = cat->threshold;
340 _set_inherited_thresholds(child);
345 void xbt_log_threshold_set(xbt_log_category_t cat, e_xbt_log_priority_t threshold)
347 cat->threshold = threshold;
348 cat->isThreshInherited = 0;
350 _set_inherited_thresholds(cat);
353 static xbt_log_setting_t _xbt_log_parse_setting(const char *control_string)
355 const char *orig_control_string = control_string;
356 xbt_log_setting_t set;
358 if (!*control_string)
360 XBT_DEBUG("Parse log setting '%s'", control_string);
362 control_string += strspn(control_string, " ");
363 const char* name = control_string;
364 control_string += strcspn(control_string, ".:= ");
365 const char* option = control_string;
366 control_string += strcspn(control_string, ":= ");
367 const char* value = control_string;
369 xbt_assert(*option == '.' && (*value == '=' || *value == ':'), "Invalid control string '%s'", orig_control_string);
371 size_t name_len = option - name;
373 size_t option_len = value - option;
376 if (strncmp(option, "threshold", option_len) == 0) {
377 XBT_DEBUG("New priority name = %s", value);
379 for (i = 0; i < xbt_log_priority_infinite; i++) {
380 if (strcasecmp(value, xbt_log_priority_names[i]) == 0) {
381 XBT_DEBUG("This is priority %d", i);
386 if(i<XBT_LOG_STATIC_THRESHOLD){
387 fprintf(stderr, "Priority '%s' (in setting '%s') is above allowed priority '%s'.\n\n"
388 "Compiling SimGrid with -DNDEBUG forbids the levels 'trace' and 'debug'\n"
389 "while -DNLOG forbids any logging, at any level.",
390 value, name, xbt_log_priority_names[XBT_LOG_STATIC_THRESHOLD]);
392 }else if (i < xbt_log_priority_infinite) {
393 set.thresh = (e_xbt_log_priority_t)i;
395 throw std::invalid_argument(simgrid::xbt::string_printf(
396 "Unknown priority name: %s (must be one of: trace,debug,verbose,info,warning,error,critical)", value));
398 } else if (strncmp(option, "additivity", option_len) == 0) {
399 set.additivity = (strcasecmp(value, "ON") == 0 || strcasecmp(value, "YES") == 0 || strcmp(value, "1") == 0);
400 } else if (strncmp(option, "appender", option_len) == 0) {
401 if (strncmp(value, "file:", 5) == 0) {
402 set.appender = xbt_log_appender_file_new(value + 5);
403 } else if (strncmp(value, "rollfile:", 9) == 0) {
404 set.appender = xbt_log_appender2_file_new(value + 9, 1);
405 } else if (strncmp(value, "splitfile:", 10) == 0) {
406 set.appender = xbt_log_appender2_file_new(value + 10, 0);
407 } else if (strcmp(value, "stderr") == 0) {
408 set.appender = xbt_log_appender_stream(stderr);
409 } else if (strcmp(value, "stdout") == 0) {
410 set.appender = xbt_log_appender_stream(stdout);
412 throw std::invalid_argument(simgrid::xbt::string_printf("Unknown appender log type: '%s'", value));
414 } else if (strncmp(option, "fmt", option_len) == 0) {
415 set.fmt = std::string(value);
417 xbt_die("Unknown setting of the log category: '%.*s'", static_cast<int>(option_len), option);
419 set.catname = std::string(name, name_len);
421 XBT_DEBUG("This is for cat '%s'", set.catname.c_str());
426 static xbt_log_category_t _xbt_log_cat_searchsub(xbt_log_category_t cat, const char* name)
428 XBT_DEBUG("Search '%s' into '%s' (firstChild='%s'; nextSibling='%s')", name,
429 cat->name, (cat->firstChild ? cat->firstChild->name : "none"),
430 (cat->nextSibling ? cat->nextSibling->name : "none"));
431 if (strcmp(cat->name, name) == 0)
434 for (xbt_log_category_t child = cat->firstChild; child != nullptr; child = child->nextSibling) {
435 XBT_DEBUG("Dig into %s", child->name);
436 xbt_log_category_t res = _xbt_log_cat_searchsub(child, name);
444 void xbt_log_control_set(const char *control_string)
448 XBT_DEBUG("Parse log settings '%s'", control_string);
450 /* Special handling of no_loc request, which asks for any file localization to be omitted (for tesh runs) */
451 if (strcmp(control_string, "no_loc") == 0) {
455 /* Split the string, and remove empty entries
456 Parse each entry and either use it right now (if the category was already created), or store it for further use */
457 std::string parsed_control_string(control_string);
458 boost::escaped_list_separator<char> sep("\\", " ", "\"'");
459 boost::tokenizer<boost::escaped_list_separator<char>> tok(parsed_control_string, sep);
460 for (const auto& str : tok) {
464 xbt_log_setting_t set = _xbt_log_parse_setting(str.c_str());
465 xbt_log_category_t cat = _xbt_log_cat_searchsub(&_XBT_LOGV(XBT_LOG_ROOT_CAT), set.catname.c_str());
468 XBT_DEBUG("Apply directly");
469 _xbt_log_cat_apply_set(cat, set);
471 XBT_DEBUG("Store for further application");
472 XBT_DEBUG("push %p to the settings", &set);
473 xbt_log_settings().emplace_back(std::move(set));
478 void xbt_log_appender_set(xbt_log_category_t cat, xbt_log_appender_t app)
481 if (cat->appender->free_)
482 cat->appender->free_(cat->appender);
483 xbt_free(cat->appender);
488 void xbt_log_layout_set(xbt_log_category_t cat, xbt_log_layout_t lay)
490 DISABLE_XBT_LOG_CAT_INIT();
491 if (!cat->appender) {
492 XBT_VERB ("No appender to category %s. Setting the file appender as default", cat->name);
493 xbt_log_appender_set(cat, xbt_log_appender_file_new(nullptr));
496 if (cat->layout->free_) {
497 cat->layout->free_(cat->layout);
499 xbt_free(cat->layout);
502 xbt_log_additivity_set(cat, 0);
505 void xbt_log_additivity_set(xbt_log_category_t cat, int additivity)
507 cat->additivity = additivity;
510 static void xbt_log_help()
513 "Description of the logging output:\n"
515 " Threshold configuration: --log=CATEGORY_NAME.thres:PRIORITY_LEVEL\n"
516 " CATEGORY_NAME: defined in code with function 'XBT_LOG_NEW_CATEGORY'\n"
517 " PRIORITY_LEVEL: the level to print (trace,debug,verbose,info,warning,error,critical)\n"
518 " -> trace: enter and return of some functions\n"
519 " -> debug: crufty output\n"
520 " -> verbose: verbose output for the user wanting more\n"
521 " -> info: output about the regular functioning\n"
522 " -> warning: minor issue encountered\n"
523 " -> error: issue encountered\n"
524 " -> critical: major issue encountered\n"
525 " The default priority level is 'info'.\n"
527 " Format configuration: --log=CATEGORY_NAME.fmt:FORMAT\n"
528 " FORMAT string may contain:\n"
529 " -> %%%%: the %% char\n"
530 " -> %%n: platform-dependent line separator (LOG4J compatible)\n"
531 " -> %%e: plain old space (SimGrid extension)\n"
533 " -> %%m: user-provided message\n"
535 " -> %%c: Category name (LOG4J compatible)\n"
536 " -> %%p: Priority name (LOG4J compatible)\n"
538 " -> %%h: Hostname (SimGrid extension)\n"
539 " -> %%a: Actor name (SimGrid extension)\n"
540 " -> %%t: Thread \"name\" (LOG4J compatible -- actually the address of the thread in memory)\n"
541 " -> %%i: Process PID (SimGrid extension -- this is a 'i' as in 'i'dea)\n"
543 " -> %%F: file name where the log event was raised (LOG4J compatible)\n"
544 " -> %%l: location where the log event was raised (LOG4J compatible, like '%%F:%%L' -- this is a l as "
546 " -> %%L: line number where the log event was raised (LOG4J compatible)\n"
547 " -> %%M: function name (LOG4J compatible -- called method name here of course).\n"
549 " -> %%b: full backtrace (Called %%throwable in LOG4J). Defined only under windows or when using the "
551 " backtrace() is not defined elsewhere, and we only have a fallback for windows boxes, not "
552 "mac ones for example.\n"
553 " -> %%B: short backtrace (only the first line of the %%b). Called %%throwable{short} in LOG4J; "
554 "defined where %%b is.\n"
556 " -> %%d: date (UNIX-like epoch)\n"
557 " -> %%r: application age (time elapsed since the beginning of the application)\n"
559 " Category appender: --log=CATEGORY_NAME.app:APPENDER\n"
560 " APPENDER may be:\n"
561 " -> stdout or stderr: standard output streams\n"
562 " -> file:NAME: append to file with given name\n"
563 " -> splitfile:SIZE:NAME: append to files with maximum size SIZE per file.\n"
564 " NAME may contain the %% wildcard as a placeholder for the file number.\n"
565 " -> rollfile:SIZE:NAME: append to file with maximum size SIZE.\n"
567 " Category additivity: --log=CATEGORY_NAME.add:VALUE\n"
568 " VALUE: '0', '1', 'no', 'yes', 'on', or 'off'\n"
571 " --help-log-categories Display the current hierarchy of log categories.\n"
572 " --log=no_loc Don't print file names in messages (for tesh tests).\n");
575 static void xbt_log_help_categories_rec(xbt_log_category_t category, const std::string& prefix)
580 std::string this_prefix(prefix);
581 std::string child_prefix(prefix);
582 if (category->parent) {
583 this_prefix += " \\_ ";
584 child_prefix += " | ";
587 std::vector<xbt_log_category_t> cats;
588 for (xbt_log_category_t cat = category; cat != nullptr; cat = cat->nextSibling)
591 std::sort(begin(cats), end(cats),
592 [](const s_xbt_log_category_t* a, const s_xbt_log_category_t* b) { return strcmp(a->name, b->name) < 0; });
594 for (auto const& cat : cats) {
595 XBT_HELP("%s%s: %s", this_prefix.c_str(), cat->name, cat->description);
596 if (cat == cats.back() && category->parent)
597 child_prefix[child_prefix.rfind('|')] = ' ';
598 xbt_log_help_categories_rec(cat->firstChild, child_prefix);
602 static void xbt_log_help_categories()
604 XBT_HELP("Current log category hierarchy:");
605 xbt_log_help_categories_rec(&_XBT_LOGV(XBT_LOG_ROOT_CAT), " ");