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 "src/xbt_modinter.h"
10 #include "xbt/asserts.h"
11 #include "xbt/dynar.h"
13 #include "xbt/string.hpp"
21 int xbt_log_no_loc = 0; /* if set to true (with --log=no_loc), file localization will be omitted (for tesh tests) */
22 static std::recursive_mutex* log_cat_init_mutex = nullptr;
24 /** @addtogroup XBT_log
26 * For more information, please refer to @ref outcomes_logs Section.
29 xbt_log_appender_t xbt_log_default_appender = nullptr; /* set in log_init */
30 xbt_log_layout_t xbt_log_default_layout = nullptr; /* set in log_init */
32 struct xbt_log_setting_t {
35 e_xbt_log_priority_t thresh = xbt_log_priority_uninitialized;
37 xbt_log_appender_t appender = nullptr;
40 // This function is here to avoid static initialization order fiasco
41 static std::vector<xbt_log_setting_t>& xbt_log_settings()
43 static std::vector<xbt_log_setting_t> value;
47 constexpr std::array<const char*, 8> xbt_log_priority_names{
48 {"NONE", "TRACE", "DEBUG", "VERBOSE", "INFO", "WARNING", "ERROR", "CRITICAL"}};
50 s_xbt_log_category_t _XBT_LOGV(XBT_LOG_ROOT_CAT) = {
52 nullptr /* firstChild */,
53 nullptr /* nextSibling */,
55 "The common ancestor for all categories",
57 xbt_log_priority_uninitialized /* threshold */,
58 0 /* isThreshInherited */,
59 nullptr /* appender */,
64 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(log, xbt, "Loggings from the logging mechanism itself");
66 /* create the default appender and install it in the root category,
67 which were already created (damnit. Too slow little beetle) */
68 void xbt_log_preinit(void)
70 xbt_log_default_appender = xbt_log_appender_stream(stderr);
71 xbt_log_default_layout = xbt_log_layout_simple_new(nullptr);
72 _XBT_LOGV(XBT_LOG_ROOT_CAT).appender = xbt_log_default_appender;
73 _XBT_LOGV(XBT_LOG_ROOT_CAT).layout = xbt_log_default_layout;
74 log_cat_init_mutex = new std::recursive_mutex();
77 static void xbt_log_help();
78 static void xbt_log_help_categories();
80 /** @brief Get all logging settings from the command line
82 * xbt_log_control_set() is called on each string we got from cmd line
84 void xbt_log_init(int *argc, char **argv)
86 unsigned help_requested = 0; /* 1: logs; 2: categories */
88 int parse_args = 1; // Stop parsing the parameters once we found '--'
90 xbt_log_control_set("xbt_help.app:stdout xbt_help.threshold:VERBOSE xbt_help.fmt:%m%n");
92 /* Set logs and init log submodule */
93 for (int i = 1; i < *argc; i++) {
94 if (strcmp("--", argv[i]) == 0) {
96 argv[j++] = argv[i]; // Keep the '--' for sg_config
97 } else if (parse_args && strncmp(argv[i], "--log=", strlen("--log=")) == 0) {
98 char* opt = strchr(argv[i], '=');
100 xbt_log_control_set(opt);
101 XBT_DEBUG("Did apply '%s' as log setting", opt);
102 } else if (parse_args && strcmp(argv[i], "--help-logs") == 0) {
103 help_requested |= 1U;
104 } else if (parse_args && strcmp(argv[i], "--help-log-categories") == 0) {
105 help_requested |= 2U;
115 if (help_requested) {
116 if (help_requested & 1)
118 if (help_requested & 2)
119 xbt_log_help_categories();
124 static void log_cat_exit(const s_xbt_log_category_t* cat)
127 if (cat->appender->free_)
128 cat->appender->free_(cat->appender);
129 xbt_free(cat->appender);
132 if (cat->layout->free_)
133 cat->layout->free_(cat->layout);
134 xbt_free(cat->layout);
137 for (auto const* child = cat->firstChild; child != nullptr; child = child->nextSibling)
141 void xbt_log_postexit(void)
143 XBT_VERB("Exiting log");
144 delete log_cat_init_mutex;
145 log_cat_exit(&_XBT_LOGV(XBT_LOG_ROOT_CAT));
148 /* Size of the static string in which we build the log string */
149 static constexpr size_t XBT_LOG_STATIC_BUFFER_SIZE = 2048;
150 /* Minimum size of the dynamic string in which we build the log string
151 (should be greater than XBT_LOG_STATIC_BUFFER_SIZE) */
152 static constexpr size_t XBT_LOG_DYNAMIC_BUFFER_SIZE = 4096;
154 void _xbt_log_event_log(xbt_log_event_t ev, const char *fmt, ...)
156 const xbt_log_category_s* cat = ev->cat;
158 xbt_assert(ev->priority >= 0, "Negative logging priority naturally forbidden");
159 xbt_assert(static_cast<size_t>(ev->priority) < xbt_log_priority_names.size(),
160 "Priority %d is greater than the biggest allowed value", ev->priority);
163 const s_xbt_log_appender_t* appender = cat->appender;
165 if (appender != nullptr) {
166 xbt_assert(cat->layout, "No valid layout for the appender of category %s", cat->name);
168 /* First, try with a static buffer */
170 std::array<char, XBT_LOG_STATIC_BUFFER_SIZE> buff;
171 ev->buffer = buff.data();
172 ev->buffer_size = buff.size();
173 va_start(ev->ap, fmt);
174 done = cat->layout->do_layout(cat->layout, ev, fmt);
176 ev->buffer = nullptr; // Calm down, static analyzers, this pointer to local array won't leak out of the scope.
178 appender->do_append(appender, buff.data());
180 /* The static buffer was too small, use a dynamically expanded one */
181 ev->buffer_size = XBT_LOG_DYNAMIC_BUFFER_SIZE;
182 ev->buffer = static_cast<char*>(xbt_malloc(ev->buffer_size));
184 va_start(ev->ap, fmt);
185 done = cat->layout->do_layout(cat->layout, ev, fmt);
189 ev->buffer_size *= 2;
190 ev->buffer = static_cast<char*>(xbt_realloc(ev->buffer, ev->buffer_size));
192 appender->do_append(appender, ev->buffer);
193 xbt_free(ev->buffer);
197 if (!cat->additivity)
205 * The standard logging macros use _XBT_LOG_ISENABLED, which calls _xbt_log_cat_init(). Thus, if we want to avoid an
206 * infinite recursion, we can not use the standard logging macros in _xbt_log_cat_init(), and in all functions called
209 * To circumvent the problem, we define the macro DISABLE_XBT_LOG_CAT_INIT() to hide the real _xbt_log_cat_init(). The
210 * macro has to be called at the beginning of the affected functions.
212 static int fake_xbt_log_cat_init(xbt_log_category_t, e_xbt_log_priority_t)
216 #define DISABLE_XBT_LOG_CAT_INIT() \
217 int (*_xbt_log_cat_init)(xbt_log_category_t, e_xbt_log_priority_t) XBT_ATTRIB_UNUSED = fake_xbt_log_cat_init;
219 static void _xbt_log_cat_apply_set(xbt_log_category_t category, const xbt_log_setting_t& setting)
221 DISABLE_XBT_LOG_CAT_INIT();
222 if (setting.thresh != xbt_log_priority_uninitialized) {
223 xbt_log_threshold_set(category, setting.thresh);
225 XBT_DEBUG("Apply settings for category '%s': set threshold to %s (=%d)",
226 category->name, xbt_log_priority_names[category->threshold], category->threshold);
229 if (not setting.fmt.empty()) {
230 xbt_log_layout_set(category, xbt_log_layout_format_new(setting.fmt.c_str()));
232 XBT_DEBUG("Apply settings for category '%s': set format to %s", category->name, setting.fmt.c_str());
235 if (setting.additivity != -1) {
236 xbt_log_additivity_set(category, setting.additivity);
238 XBT_DEBUG("Apply settings for category '%s': set additivity to %s", category->name,
239 (setting.additivity ? "on" : "off"));
241 if (setting.appender) {
242 xbt_log_appender_set(category, setting.appender);
243 if (!category->layout)
244 xbt_log_layout_set(category, xbt_log_layout_simple_new(nullptr));
245 category->additivity = 0;
246 XBT_DEBUG("Set %p as appender of category '%s'", setting.appender, category->name);
251 * This gets called the first time a category is referenced and performs the initialization.
252 * Also resets threshold to inherited!
254 int _xbt_log_cat_init(xbt_log_category_t category, e_xbt_log_priority_t priority)
256 DISABLE_XBT_LOG_CAT_INIT();
257 if (category->initialized)
258 return priority >= category->threshold;
260 if (log_cat_init_mutex != nullptr)
261 log_cat_init_mutex->lock();
263 XBT_DEBUG("Initializing category '%s' (firstChild=%s, nextSibling=%s)", category->name,
264 (category->firstChild ? category->firstChild->name : "none"),
265 (category->nextSibling ? category->nextSibling->name : "none"));
267 if (category == &_XBT_LOGV(XBT_LOG_ROOT_CAT)) {
268 category->threshold = xbt_log_priority_info;
269 category->appender = xbt_log_default_appender;
270 category->layout = xbt_log_default_layout;
272 if (!category->parent)
273 category->parent = &_XBT_LOGV(XBT_LOG_ROOT_CAT);
275 XBT_DEBUG("Set %s (%s) as father of %s ", category->parent->name,
276 (category->parent->initialized ? xbt_log_priority_names[category->parent->threshold] : "uninited"),
278 xbt_log_parent_set(category, category->parent);
280 if (XBT_LOG_ISENABLED(log, xbt_log_priority_debug)) {
282 const xbt_log_category_s* cpp = category->parent->firstChild;
284 res += std::string(" ") + cpp->name;
285 cpp = cpp->nextSibling;
288 XBT_DEBUG("Children of %s:%s; nextSibling: %s", category->parent->name, res.c_str(),
289 (category->parent->nextSibling ? category->parent->nextSibling->name : "none"));
293 /* Apply the control */
294 auto iset = std::find_if(begin(xbt_log_settings()), end(xbt_log_settings()),
295 [category](const xbt_log_setting_t& s) { return s.catname == category->name; });
296 if (iset != xbt_log_settings().end()) {
297 _xbt_log_cat_apply_set(category, *iset);
298 xbt_log_settings().erase(iset);
300 XBT_DEBUG("Category '%s': inherited threshold = %s (=%d)", category->name,
301 xbt_log_priority_names[category->threshold], category->threshold);
304 category->initialized = 1;
305 if (log_cat_init_mutex != nullptr)
306 log_cat_init_mutex->unlock();
307 return priority >= category->threshold;
310 void xbt_log_parent_set(xbt_log_category_t cat, xbt_log_category_t parent)
312 xbt_assert(cat, "NULL category to be given a parent");
313 xbt_assert(parent, "The parent category of %s is NULL", cat->name);
315 /* if the category is initialized, unlink from current parent */
316 if (cat->initialized) {
317 xbt_log_category_t *cpp = &cat->parent->firstChild;
319 while (*cpp != cat && *cpp != nullptr) {
320 cpp = &(*cpp)->nextSibling;
323 xbt_assert(*cpp == cat);
324 *cpp = cat->nextSibling;
327 cat->parent = parent;
328 cat->nextSibling = parent->firstChild;
330 parent->firstChild = cat;
332 if (!parent->initialized)
333 _xbt_log_cat_init(parent, xbt_log_priority_uninitialized /* ignored */ );
335 cat->threshold = parent->threshold;
337 cat->isThreshInherited = 1;
340 static void _set_inherited_thresholds(const s_xbt_log_category_t* cat)
342 xbt_log_category_t child = cat->firstChild;
344 for (; child != nullptr; child = child->nextSibling) {
345 if (child->isThreshInherited) {
346 if (cat != &_XBT_LOGV(log))
347 XBT_VERB("Set category threshold of %s to %s (=%d)",
348 child->name, xbt_log_priority_names[cat->threshold], cat->threshold);
349 child->threshold = cat->threshold;
350 _set_inherited_thresholds(child);
355 void xbt_log_threshold_set(xbt_log_category_t cat, e_xbt_log_priority_t threshold)
357 cat->threshold = threshold;
358 cat->isThreshInherited = 0;
360 _set_inherited_thresholds(cat);
363 static xbt_log_setting_t _xbt_log_parse_setting(const char *control_string)
365 const char *orig_control_string = control_string;
366 xbt_log_setting_t set;
368 if (!*control_string)
370 XBT_DEBUG("Parse log setting '%s'", control_string);
372 control_string += strspn(control_string, " ");
373 const char* name = control_string;
374 control_string += strcspn(control_string, ".:= ");
375 const char* option = control_string;
376 control_string += strcspn(control_string, ":= ");
377 const char* value = control_string;
379 xbt_assert(*option == '.' && (*value == '=' || *value == ':'), "Invalid control string '%s'", orig_control_string);
381 size_t name_len = option - name;
383 size_t option_len = value - option;
386 if (strncmp(option, "threshold", option_len) == 0) {
387 XBT_DEBUG("New priority name = %s", value);
389 for (i = 0; i < xbt_log_priority_infinite; i++) {
390 if (strcasecmp(value, xbt_log_priority_names[i]) == 0) {
391 XBT_DEBUG("This is priority %d", i);
396 if(i<XBT_LOG_STATIC_THRESHOLD){
397 fprintf(stderr, "Priority '%s' (in setting '%s') is above allowed priority '%s'.\n\n"
398 "Compiling SimGrid with -DNDEBUG forbids the levels 'trace' and 'debug'\n"
399 "while -DNLOG forbids any logging, at any level.",
400 value, name, xbt_log_priority_names[XBT_LOG_STATIC_THRESHOLD]);
402 }else if (i < xbt_log_priority_infinite) {
403 set.thresh = (e_xbt_log_priority_t)i;
405 throw std::invalid_argument(simgrid::xbt::string_printf(
406 "Unknown priority name: %s (must be one of: trace,debug,verbose,info,warning,error,critical)", value));
408 } else if (strncmp(option, "additivity", option_len) == 0) {
409 set.additivity = (strcasecmp(value, "ON") == 0 || strcasecmp(value, "YES") == 0 || strcmp(value, "1") == 0);
410 } else if (strncmp(option, "appender", option_len) == 0) {
411 if (strncmp(value, "file:", 5) == 0) {
412 set.appender = xbt_log_appender_file_new(value + 5);
413 } else if (strncmp(value, "rollfile:", 9) == 0) {
414 set.appender = xbt_log_appender2_file_new(value + 9, 1);
415 } else if (strncmp(value, "splitfile:", 10) == 0) {
416 set.appender = xbt_log_appender2_file_new(value + 10, 0);
417 } else if (strcmp(value, "stderr") == 0) {
418 set.appender = xbt_log_appender_stream(stderr);
419 } else if (strcmp(value, "stdout") == 0) {
420 set.appender = xbt_log_appender_stream(stdout);
422 throw std::invalid_argument(simgrid::xbt::string_printf("Unknown appender log type: '%s'", value));
424 } else if (strncmp(option, "fmt", option_len) == 0) {
425 set.fmt = std::string(value);
427 xbt_die("Unknown setting of the log category: '%.*s'", static_cast<int>(option_len), option);
429 set.catname = std::string(name, name_len);
431 XBT_DEBUG("This is for cat '%s'", set.catname.c_str());
436 static xbt_log_category_t _xbt_log_cat_searchsub(xbt_log_category_t cat, const char* name)
438 XBT_DEBUG("Search '%s' into '%s' (firstChild='%s'; nextSibling='%s')", name,
439 cat->name, (cat->firstChild ? cat->firstChild->name : "none"),
440 (cat->nextSibling ? cat->nextSibling->name : "none"));
441 if (strcmp(cat->name, name) == 0)
444 for (xbt_log_category_t child = cat->firstChild; child != nullptr; child = child->nextSibling) {
445 XBT_DEBUG("Dig into %s", child->name);
446 xbt_log_category_t res = _xbt_log_cat_searchsub(child, name);
456 * @param control_string What to parse
458 * Typically passed a command-line argument. The string has the syntax:
460 * ( [category] "." [keyword] ":" value (" ")... )...
462 * where [category] is one the category names (see @ref XBT_log_cats for a complete list of the ones defined in the
463 * SimGrid library) and keyword is one of the following:
465 * - thres: category's threshold priority. Possible values:
466 * TRACE,DEBUG,VERBOSE,INFO,WARNING,ERROR,CRITICAL
467 * - add or additivity: whether the logging actions must be passed to the parent category.
468 * Possible values: 0, 1, no, yes, on, off.
469 * Default value: yes.
470 * - fmt: the format to use. See @ref log_use_conf_fmt for more information.
471 * - app or appender: the appender to use. See @ref log_use_conf_app for more information.
473 void xbt_log_control_set(const char *control_string)
475 /* To split the string in commands, and the cursors */
476 xbt_dynar_t set_strings;
482 XBT_DEBUG("Parse log settings '%s'", control_string);
484 /* Special handling of no_loc request, which asks for any file localization to be omitted (for tesh runs) */
485 if (strcmp(control_string, "no_loc") == 0) {
489 /* split the string, and remove empty entries */
490 set_strings = xbt_str_split_quoted(control_string);
492 if (xbt_dynar_is_empty(set_strings)) { /* vicious user! */
493 xbt_dynar_free(&set_strings);
497 /* Parse each entry and either use it right now (if the category was already created), or store it for further use */
498 xbt_dynar_foreach(set_strings, cpt, str) {
499 xbt_log_setting_t set = _xbt_log_parse_setting(str);
500 xbt_log_category_t cat = _xbt_log_cat_searchsub(&_XBT_LOGV(XBT_LOG_ROOT_CAT), set.catname.c_str());
503 XBT_DEBUG("Apply directly");
504 _xbt_log_cat_apply_set(cat, set);
506 XBT_DEBUG("Store for further application");
507 XBT_DEBUG("push %p to the settings", &set);
508 xbt_log_settings().emplace_back(std::move(set));
511 xbt_dynar_free(&set_strings);
514 void xbt_log_appender_set(xbt_log_category_t cat, xbt_log_appender_t app)
517 if (cat->appender->free_)
518 cat->appender->free_(cat->appender);
519 xbt_free(cat->appender);
524 void xbt_log_layout_set(xbt_log_category_t cat, xbt_log_layout_t lay)
526 DISABLE_XBT_LOG_CAT_INIT();
527 if (!cat->appender) {
528 XBT_VERB ("No appender to category %s. Setting the file appender as default", cat->name);
529 xbt_log_appender_set(cat, xbt_log_appender_file_new(nullptr));
532 if (cat->layout->free_) {
533 cat->layout->free_(cat->layout);
535 xbt_free(cat->layout);
538 xbt_log_additivity_set(cat, 0);
541 void xbt_log_additivity_set(xbt_log_category_t cat, int additivity)
543 cat->additivity = additivity;
546 static void xbt_log_help()
549 "Description of the logging output:\n"
551 " Threshold configuration: --log=CATEGORY_NAME.thres:PRIORITY_LEVEL\n"
552 " CATEGORY_NAME: defined in code with function 'XBT_LOG_NEW_CATEGORY'\n"
553 " PRIORITY_LEVEL: the level to print (trace,debug,verbose,info,warning,error,critical)\n"
554 " -> trace: enter and return of some functions\n"
555 " -> debug: crufty output\n"
556 " -> verbose: verbose output for the user wanting more\n"
557 " -> info: output about the regular functioning\n"
558 " -> warning: minor issue encountered\n"
559 " -> error: issue encountered\n"
560 " -> critical: major issue encountered\n"
561 " The default priority level is 'info'.\n"
563 " Format configuration: --log=CATEGORY_NAME.fmt:FORMAT\n"
564 " FORMAT string may contain:\n"
565 " -> %%%%: the %% char\n"
566 " -> %%n: platform-dependent line separator (LOG4J compatible)\n"
567 " -> %%e: plain old space (SimGrid extension)\n"
569 " -> %%m: user-provided message\n"
571 " -> %%c: Category name (LOG4J compatible)\n"
572 " -> %%p: Priority name (LOG4J compatible)\n"
574 " -> %%h: Hostname (SimGrid extension)\n"
575 " -> %%P: Process name (SimGrid extension)\n"
576 " -> %%t: Thread \"name\" (LOG4J compatible -- actually the address of the thread in memory)\n"
577 " -> %%i: Process PID (SimGrid extension -- this is a 'i' as in 'i'dea)\n"
579 " -> %%F: file name where the log event was raised (LOG4J compatible)\n"
580 " -> %%l: location where the log event was raised (LOG4J compatible, like '%%F:%%L' -- this is a l as "
582 " -> %%L: line number where the log event was raised (LOG4J compatible)\n"
583 " -> %%M: function name (LOG4J compatible -- called method name here of course).\n"
585 " -> %%b: full backtrace (Called %%throwable in LOG4J). Defined only under windows or when using the "
587 " backtrace() is not defined elsewhere, and we only have a fallback for windows boxes, not "
588 "mac ones for example.\n"
589 " -> %%B: short backtrace (only the first line of the %%b). Called %%throwable{short} in LOG4J; "
590 "defined where %%b is.\n"
592 " -> %%d: date (UNIX-like epoch)\n"
593 " -> %%r: application age (time elapsed since the beginning of the application)\n"
595 " Category appender: --log=CATEGORY_NAME.app:APPENDER\n"
596 " APPENDER may be:\n"
597 " -> stdout or stderr: standard output streams\n"
598 " -> file:NAME: append to file with given name\n"
599 " -> splitfile:SIZE:NAME: append to files with maximum size SIZE per file.\n"
600 " NAME may contain the %% wildcard as a placeholder for the file number.\n"
601 " -> rollfile:SIZE:NAME: append to file with maximum size SIZE.\n"
603 " Category additivity: --log=CATEGORY_NAME.add:VALUE\n"
604 " VALUE: '0', '1', 'no', 'yes', 'on', or 'off'\n"
607 " --help-log-categories Display the current hierarchy of log categories.\n"
608 " --log=no_loc Don't print file names in messages (for tesh tests).\n");
611 static void xbt_log_help_categories_rec(xbt_log_category_t category, const std::string& prefix)
616 std::string this_prefix(prefix);
617 std::string child_prefix(prefix);
618 if (category->parent) {
619 this_prefix += " \\_ ";
620 child_prefix += " | ";
623 std::vector<xbt_log_category_t> cats;
624 for (xbt_log_category_t cat = category; cat != nullptr; cat = cat->nextSibling)
627 std::sort(begin(cats), end(cats),
628 [](const s_xbt_log_category_t* a, const s_xbt_log_category_t* b) { return strcmp(a->name, b->name) < 0; });
630 for (auto const& cat : cats) {
631 XBT_HELP("%s%s: %s", this_prefix.c_str(), cat->name, cat->description);
632 if (cat == cats.back() && category->parent)
633 child_prefix[child_prefix.rfind('|')] = ' ';
634 xbt_log_help_categories_rec(cat->firstChild, child_prefix);
638 static void xbt_log_help_categories()
640 XBT_HELP("Current log category hierarchy:");
641 xbt_log_help_categories_rec(&_XBT_LOGV(XBT_LOG_ROOT_CAT), " ");