1 /* log - a generic logging facility in the spirit of log4j */
3 /* Copyright (c) 2004-2019. 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_modinter.h"
9 #include "src/xbt/log_private.hpp"
10 #include "xbt/asserts.h"
11 #include "xbt/dynar.h"
16 int xbt_log_no_loc = 0; /* if set to true (with --log=no_loc), file localization will be omitted (for tesh tests) */
17 static std::recursive_mutex* log_cat_init_mutex = nullptr;
19 /** @addtogroup XBT_log
21 * For more information, please refer to @ref outcomes_logs Section.
24 xbt_log_appender_t xbt_log_default_appender = nullptr; /* set in log_init */
25 xbt_log_layout_t xbt_log_default_layout = nullptr; /* set in log_init */
30 e_xbt_log_priority_t thresh;
32 xbt_log_appender_t appender;
33 } s_xbt_log_setting_t;
35 typedef s_xbt_log_setting_t* xbt_log_setting_t;
37 static xbt_dynar_t xbt_log_settings = nullptr;
39 static void _free_setting(void *s)
41 xbt_log_setting_t set = *(xbt_log_setting_t *) s;
43 xbt_free(set->catname);
49 static void _xbt_log_cat_apply_set(xbt_log_category_t category, xbt_log_setting_t setting);
51 const char *xbt_log_priority_names[8] = {
62 s_xbt_log_category_t _XBT_LOGV(XBT_LOG_ROOT_CAT) = {
64 nullptr /* firstChild */,
65 nullptr /* nextSibling */,
67 "The common ancestor for all categories",
69 xbt_log_priority_uninitialized /* threshold */,
70 0 /* isThreshInherited */,
71 nullptr /* appender */,
76 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(log, xbt, "Loggings from the logging mechanism itself");
78 /* create the default appender and install it in the root category,
79 which were already created (damnit. Too slow little beetle) */
80 void xbt_log_preinit(void)
82 xbt_log_default_appender = xbt_log_appender_file_new(nullptr);
83 xbt_log_default_layout = xbt_log_layout_simple_new(nullptr);
84 _XBT_LOGV(XBT_LOG_ROOT_CAT).appender = xbt_log_default_appender;
85 _XBT_LOGV(XBT_LOG_ROOT_CAT).layout = xbt_log_default_layout;
86 log_cat_init_mutex = new std::recursive_mutex();
89 static void xbt_log_help(void);
90 static void xbt_log_help_categories(void);
92 /** @brief Get all logging settings from the command line
94 * xbt_log_control_set() is called on each string we got from cmd line
96 void xbt_log_init(int *argc, char **argv)
98 unsigned help_requested = 0; /* 1: logs; 2: categories */
100 int parse_args = 1; // Stop parsing the parameters once we found '--'
102 /* Set logs and init log submodule */
103 for (int i = 1; i < *argc; i++) {
104 if (!strcmp("--", argv[i])) {
106 argv[j++] = argv[i]; // Keep the '--' for sg_config
107 } else if (parse_args && !strncmp(argv[i], "--log=", strlen("--log="))) {
108 char* opt = strchr(argv[i], '=');
110 xbt_log_control_set(opt);
111 XBT_DEBUG("Did apply '%s' as log setting", opt);
112 } else if (parse_args && !strcmp(argv[i], "--help-logs")) {
113 help_requested |= 1U;
114 } else if (parse_args && !strcmp(argv[i], "--help-log-categories")) {
115 help_requested |= 2U;
125 if (help_requested) {
126 if (help_requested & 1)
128 if (help_requested & 2)
129 xbt_log_help_categories();
134 static void log_cat_exit(xbt_log_category_t cat)
136 xbt_log_category_t child;
139 if (cat->appender->free_)
140 cat->appender->free_(cat->appender);
141 xbt_free(cat->appender);
144 if (cat->layout->free_)
145 cat->layout->free_(cat->layout);
146 xbt_free(cat->layout);
149 for (child = cat->firstChild; child != nullptr; child = child->nextSibling)
153 void xbt_log_postexit(void)
155 XBT_VERB("Exiting log");
156 delete log_cat_init_mutex;
157 xbt_dynar_free(&xbt_log_settings);
158 log_cat_exit(&_XBT_LOGV(XBT_LOG_ROOT_CAT));
161 /* Size of the static string in which we build the log string */
162 static constexpr size_t XBT_LOG_STATIC_BUFFER_SIZE = 2048;
163 /* Minimum size of the dynamic string in which we build the log string
164 (should be greater than XBT_LOG_STATIC_BUFFER_SIZE) */
165 static constexpr size_t XBT_LOG_DYNAMIC_BUFFER_SIZE = 4096;
167 void _xbt_log_event_log(xbt_log_event_t ev, const char *fmt, ...)
169 xbt_log_category_t cat = ev->cat;
171 xbt_assert(ev->priority >= 0, "Negative logging priority naturally forbidden");
172 xbt_assert(static_cast<size_t>(ev->priority) < sizeof(xbt_log_priority_names)/sizeof(xbt_log_priority_names[0]),
173 "Priority %d is greater than the biggest allowed value", ev->priority);
176 xbt_log_appender_t appender = cat->appender;
178 if (appender != nullptr) {
179 xbt_assert(cat->layout, "No valid layout for the appender of category %s", cat->name);
181 /* First, try with a static buffer */
183 char buff[XBT_LOG_STATIC_BUFFER_SIZE];
185 ev->buffer_size = sizeof buff;
186 va_start(ev->ap, fmt);
187 done = cat->layout->do_layout(cat->layout, ev, fmt);
190 appender->do_append(appender, buff);
193 /* The static buffer was too small, use a dynamically expanded one */
194 ev->buffer_size = XBT_LOG_DYNAMIC_BUFFER_SIZE;
195 ev->buffer = static_cast<char*>(xbt_malloc(ev->buffer_size));
197 va_start(ev->ap, fmt);
198 done = cat->layout->do_layout(cat->layout, ev, fmt);
202 ev->buffer_size *= 2;
203 ev->buffer = static_cast<char*>(xbt_realloc(ev->buffer, ev->buffer_size));
205 appender->do_append(appender, ev->buffer);
206 xbt_free(ev->buffer);
210 if (!cat->additivity)
218 * The standard logging macros use _XBT_LOG_ISENABLED, which calls _xbt_log_cat_init(). Thus, if we want to avoid an
219 * infinite recursion, we can not use the standard logging macros in _xbt_log_cat_init(), and in all functions called
222 * To circumvent the problem, we define the macro DISABLE_XBT_LOG_CAT_INIT() to hide the real _xbt_log_cat_init(). The
223 * macro has to be called at the beginning of the affected functions.
225 static int fake_xbt_log_cat_init(xbt_log_category_t, e_xbt_log_priority_t)
229 #define DISABLE_XBT_LOG_CAT_INIT() \
230 int (*_xbt_log_cat_init)(xbt_log_category_t, e_xbt_log_priority_t) XBT_ATTRIB_UNUSED = fake_xbt_log_cat_init;
232 static void _xbt_log_cat_apply_set(xbt_log_category_t category, xbt_log_setting_t setting)
234 DISABLE_XBT_LOG_CAT_INIT();
235 if (setting->thresh != xbt_log_priority_uninitialized) {
236 xbt_log_threshold_set(category, setting->thresh);
238 XBT_DEBUG("Apply settings for category '%s': set threshold to %s (=%d)",
239 category->name, xbt_log_priority_names[category->threshold], category->threshold);
243 xbt_log_layout_set(category, xbt_log_layout_format_new(setting->fmt));
245 XBT_DEBUG("Apply settings for category '%s': set format to %s", category->name, setting->fmt);
248 if (setting->additivity != -1) {
249 xbt_log_additivity_set(category, setting->additivity);
251 XBT_DEBUG("Apply settings for category '%s': set additivity to %s",
252 category->name, (setting->additivity ? "on" : "off"));
254 if (setting->appender) {
255 xbt_log_appender_set(category, setting->appender);
256 if (!category->layout)
257 xbt_log_layout_set(category, xbt_log_layout_simple_new(nullptr));
258 category->additivity = 0;
259 XBT_DEBUG("Set %p as appender of category '%s'", setting->appender, category->name);
264 * This gets called the first time a category is referenced and performs the initialization.
265 * Also resets threshold to inherited!
267 int _xbt_log_cat_init(xbt_log_category_t category, e_xbt_log_priority_t priority)
269 DISABLE_XBT_LOG_CAT_INIT();
270 if (category->initialized)
271 return priority >= category->threshold;
273 if (log_cat_init_mutex != nullptr)
274 log_cat_init_mutex->lock();
277 xbt_log_setting_t setting = nullptr;
279 XBT_DEBUG("Initializing category '%s' (firstChild=%s, nextSibling=%s)", category->name,
280 (category->firstChild ? category->firstChild->name : "none"),
281 (category->nextSibling ? category->nextSibling->name : "none"));
283 if (category == &_XBT_LOGV(XBT_LOG_ROOT_CAT)) {
284 category->threshold = xbt_log_priority_info;
285 category->appender = xbt_log_default_appender;
286 category->layout = xbt_log_default_layout;
288 if (!category->parent)
289 category->parent = &_XBT_LOGV(XBT_LOG_ROOT_CAT);
291 XBT_DEBUG("Set %s (%s) as father of %s ", category->parent->name,
292 (category->parent->initialized ? xbt_log_priority_names[category->parent->threshold] : "uninited"),
294 xbt_log_parent_set(category, category->parent);
296 if (XBT_LOG_ISENABLED(log, xbt_log_priority_debug)) {
298 xbt_log_category_t cpp = category->parent->firstChild;
300 res += std::string(" ") + cpp->name;
301 cpp = cpp->nextSibling;
304 XBT_DEBUG("Children of %s:%s; nextSibling: %s", category->parent->name, res.c_str(),
305 (category->parent->nextSibling ? category->parent->nextSibling->name : "none"));
309 /* Apply the control */
310 if (xbt_log_settings) {
311 xbt_assert(category, "NULL category");
312 xbt_assert(category->name);
315 xbt_dynar_foreach(xbt_log_settings, cursor, setting) {
316 xbt_assert(setting, "Damnit, NULL cat in the list");
317 xbt_assert(setting->catname, "NULL setting(=%p)->catname", (void *) setting);
319 if (!strcmp(setting->catname, category->name)) {
321 _xbt_log_cat_apply_set(category, setting);
322 xbt_dynar_cursor_rm(xbt_log_settings, &cursor);
327 XBT_DEBUG("Category '%s': inherited threshold = %s (=%d)",
328 category->name, xbt_log_priority_names[category->threshold], category->threshold);
331 category->initialized = 1;
332 if (log_cat_init_mutex != nullptr)
333 log_cat_init_mutex->unlock();
334 return priority >= category->threshold;
337 void xbt_log_parent_set(xbt_log_category_t cat, xbt_log_category_t parent)
339 xbt_assert(cat, "NULL category to be given a parent");
340 xbt_assert(parent, "The parent category of %s is NULL", cat->name);
342 /* if the category is initialized, unlink from current parent */
343 if (cat->initialized) {
344 xbt_log_category_t *cpp = &cat->parent->firstChild;
346 while (*cpp != cat && *cpp != nullptr) {
347 cpp = &(*cpp)->nextSibling;
350 xbt_assert(*cpp == cat);
351 *cpp = cat->nextSibling;
354 cat->parent = parent;
355 cat->nextSibling = parent->firstChild;
357 parent->firstChild = cat;
359 if (!parent->initialized)
360 _xbt_log_cat_init(parent, xbt_log_priority_uninitialized /* ignored */ );
362 cat->threshold = parent->threshold;
364 cat->isThreshInherited = 1;
367 static void _set_inherited_thresholds(xbt_log_category_t cat)
369 xbt_log_category_t child = cat->firstChild;
371 for (; child != nullptr; child = child->nextSibling) {
372 if (child->isThreshInherited) {
373 if (cat != &_XBT_LOGV(log))
374 XBT_VERB("Set category threshold of %s to %s (=%d)",
375 child->name, xbt_log_priority_names[cat->threshold], cat->threshold);
376 child->threshold = cat->threshold;
377 _set_inherited_thresholds(child);
382 void xbt_log_threshold_set(xbt_log_category_t cat, e_xbt_log_priority_t threshold)
384 cat->threshold = threshold;
385 cat->isThreshInherited = 0;
387 _set_inherited_thresholds(cat);
390 static xbt_log_setting_t _xbt_log_parse_setting(const char *control_string)
392 const char *orig_control_string = control_string;
393 xbt_log_setting_t set = xbt_new(s_xbt_log_setting_t, 1);
395 set->catname = nullptr;
396 set->thresh = xbt_log_priority_uninitialized;
398 set->additivity = -1;
399 set->appender = nullptr;
401 if (!*control_string)
403 XBT_DEBUG("Parse log setting '%s'", control_string);
405 control_string += strspn(control_string, " ");
406 const char *name = control_string;
407 control_string += strcspn(control_string, ".:= ");
408 const char *dot = control_string;
409 control_string += strcspn(control_string, ":= ");
410 const char *eq = control_string;
412 xbt_assert(*dot == '.' || (*eq != '=' && *eq != ':'), "Invalid control string '%s'", orig_control_string);
414 if (!strncmp(dot + 1, "threshold", (size_t) (eq - dot - 1))) {
416 char *neweq = xbt_strdup(eq + 1);
419 while (*(++p) != '\0') {
420 if (*p >= 'a' && *p <= 'z') {
425 XBT_DEBUG("New priority name = %s", neweq);
426 for (i = 0; i < xbt_log_priority_infinite; i++) {
427 if (!strncmp(xbt_log_priority_names[i], neweq, p - eq)) {
428 XBT_DEBUG("This is priority %d", i);
433 if(i<XBT_LOG_STATIC_THRESHOLD){
435 "Priority '%s' (in setting '%s') is above allowed priority '%s'.\n\n"
436 "Compiling SimGrid with -DNDEBUG forbids the levels 'trace' and 'debug'\n"
437 "while -DNLOG forbids any logging, at any level.",
438 eq + 1, name, xbt_log_priority_names[XBT_LOG_STATIC_THRESHOLD]);
440 }else if (i < xbt_log_priority_infinite) {
441 set->thresh = (e_xbt_log_priority_t) i;
444 "Unknown priority name: %s (must be one of: trace,debug,verbose,info,warning,error,critical)", eq + 1);
447 } else if (!strncmp(dot + 1, "add", (size_t) (eq - dot - 1)) ||
448 !strncmp(dot + 1, "additivity", (size_t) (eq - dot - 1))) {
449 char *neweq = xbt_strdup(eq + 1);
452 while (*(++p) != '\0') {
453 if (*p >= 'a' && *p <= 'z') {
457 if (!strcmp(neweq, "ON") || !strcmp(neweq, "YES") || !strcmp(neweq, "1")) {
463 } else if (!strncmp(dot + 1, "app", (size_t) (eq - dot - 1)) ||
464 !strncmp(dot + 1, "appender", (size_t) (eq - dot - 1))) {
465 char *neweq = xbt_strdup(eq + 1);
467 if (!strncmp(neweq, "file:", 5)) {
468 set->appender = xbt_log_appender_file_new(neweq + 5);
469 }else if (!strncmp(neweq, "rollfile:", 9)) {
470 set->appender = xbt_log_appender2_file_new(neweq + 9,1);
471 }else if (!strncmp(neweq, "splitfile:", 10)) {
472 set->appender = xbt_log_appender2_file_new(neweq + 10,0);
474 THROWF(arg_error, 0, "Unknown appender log type: '%s'", neweq);
477 } else if (!strncmp(dot + 1, "fmt", (size_t) (eq - dot - 1))) {
478 set->fmt = xbt_strdup(eq + 1);
481 snprintf(buff, std::min<int>(512, eq - dot), "%s", dot + 1);
482 xbt_die("Unknown setting of the log category: '%s'", buff);
484 set->catname = (char *) xbt_malloc(dot - name + 1);
486 memcpy(set->catname, name, dot - name);
487 set->catname[dot - name] = '\0'; /* Just in case */
488 XBT_DEBUG("This is for cat '%s'", set->catname);
493 static xbt_log_category_t _xbt_log_cat_searchsub(xbt_log_category_t cat, char *name)
495 xbt_log_category_t child;
496 xbt_log_category_t res;
498 XBT_DEBUG("Search '%s' into '%s' (firstChild='%s'; nextSibling='%s')", name,
499 cat->name, (cat->firstChild ? cat->firstChild->name : "none"),
500 (cat->nextSibling ? cat->nextSibling->name : "none"));
501 if (!strcmp(cat->name, name))
504 for (child = cat->firstChild; child != nullptr; child = child->nextSibling) {
505 XBT_DEBUG("Dig into %s", child->name);
506 res = _xbt_log_cat_searchsub(child, name);
516 * @param control_string What to parse
518 * Typically passed a command-line argument. The string has the syntax:
520 * ( [category] "." [keyword] ":" value (" ")... )...
522 * where [category] is one the category names (see @ref XBT_log_cats for a complete list of the ones defined in the
523 * SimGrid library) and keyword is one of the following:
525 * - thres: category's threshold priority. Possible values:
526 * TRACE,DEBUG,VERBOSE,INFO,WARNING,ERROR,CRITICAL
527 * - add or additivity: whether the logging actions must be passed to the parent category.
528 * Possible values: 0, 1, no, yes, on, off.
529 * Default value: yes.
530 * - fmt: the format to use. See @ref log_use_conf_fmt for more information.
531 * - app or appender: the appender to use. See @ref log_use_conf_app for more information.
533 void xbt_log_control_set(const char *control_string)
535 xbt_log_setting_t set;
537 /* To split the string in commands, and the cursors */
538 xbt_dynar_t set_strings;
544 XBT_DEBUG("Parse log settings '%s'", control_string);
546 /* Special handling of no_loc request, which asks for any file localization to be omitted (for tesh runs) */
547 if (!strcmp(control_string, "no_loc")) {
551 /* some initialization if this is the first time that this get called */
552 if (xbt_log_settings == nullptr)
553 xbt_log_settings = xbt_dynar_new(sizeof(xbt_log_setting_t), _free_setting);
555 /* split the string, and remove empty entries */
556 set_strings = xbt_str_split_quoted(control_string);
558 if (xbt_dynar_is_empty(set_strings)) { /* vicious user! */
559 xbt_dynar_free(&set_strings);
563 /* Parse each entry and either use it right now (if the category was already created), or store it for further use */
564 xbt_dynar_foreach(set_strings, cpt, str) {
565 set = _xbt_log_parse_setting(str);
566 xbt_log_category_t cat = _xbt_log_cat_searchsub(&_XBT_LOGV(XBT_LOG_ROOT_CAT), set->catname);
569 XBT_DEBUG("Apply directly");
570 _xbt_log_cat_apply_set(cat, set);
571 _free_setting((void *) &set);
573 XBT_DEBUG("Store for further application");
574 XBT_DEBUG("push %p to the settings", (void *) set);
575 xbt_dynar_push(xbt_log_settings, &set);
578 xbt_dynar_free(&set_strings);
581 void xbt_log_appender_set(xbt_log_category_t cat, xbt_log_appender_t app)
584 if (cat->appender->free_)
585 cat->appender->free_(cat->appender);
586 xbt_free(cat->appender);
591 void xbt_log_layout_set(xbt_log_category_t cat, xbt_log_layout_t lay)
593 DISABLE_XBT_LOG_CAT_INIT();
594 if (!cat->appender) {
595 XBT_VERB ("No appender to category %s. Setting the file appender as default", cat->name);
596 xbt_log_appender_set(cat, xbt_log_appender_file_new(nullptr));
599 if (cat->layout->free_) {
600 cat->layout->free_(cat->layout);
602 xbt_free(cat->layout);
605 xbt_log_additivity_set(cat, 0);
608 void xbt_log_additivity_set(xbt_log_category_t cat, int additivity)
610 cat->additivity = additivity;
613 static void xbt_log_help(void)
615 printf("Description of the logging output:\n"
617 " Threshold configuration: --log=CATEGORY_NAME.thres:PRIORITY_LEVEL\n"
618 " CATEGORY_NAME: defined in code with function 'XBT_LOG_NEW_CATEGORY'\n"
619 " PRIORITY_LEVEL: the level to print (trace,debug,verbose,info,warning,error,critical)\n"
620 " -> trace: enter and return of some functions\n"
621 " -> debug: crufty output\n"
622 " -> verbose: verbose output for the user wanting more\n"
623 " -> info: output about the regular functioning\n"
624 " -> warning: minor issue encountered\n"
625 " -> error: issue encountered\n"
626 " -> critical: major issue encountered\n"
627 " The default priority level is 'info'.\n"
629 " Format configuration: --log=CATEGORY_NAME.fmt:FORMAT\n"
630 " FORMAT string may contain:\n"
631 " -> %%%%: the %% char\n"
632 " -> %%n: platform-dependent line separator (LOG4J compatible)\n"
633 " -> %%e: plain old space (SimGrid extension)\n"
635 " -> %%m: user-provided message\n"
637 " -> %%c: Category name (LOG4J compatible)\n"
638 " -> %%p: Priority name (LOG4J compatible)\n"
640 " -> %%h: Hostname (SimGrid extension)\n"
641 " -> %%P: Process name (SimGrid extension)\n"
642 " -> %%t: Thread \"name\" (LOG4J compatible -- actually the address of the thread in memory)\n"
643 " -> %%i: Process PID (SimGrid extension -- this is a 'i' as in 'i'dea)\n"
645 " -> %%F: file name where the log event was raised (LOG4J compatible)\n"
646 " -> %%l: location where the log event was raised (LOG4J compatible, like '%%F:%%L' -- this is a l as "
648 " -> %%L: line number where the log event was raised (LOG4J compatible)\n"
649 " -> %%M: function name (LOG4J compatible -- called method name here of course).\n"
650 " Defined only when using gcc because there is no __func__ elsewhere.\n"
652 " -> %%b: full backtrace (Called %%throwable in LOG4J). Defined only under windows or when using the "
654 " backtrace() is not defined elsewhere, and we only have a fallback for windows boxes, not "
655 "mac ones for example.\n"
656 " -> %%B: short backtrace (only the first line of the %%b). Called %%throwable{short} in LOG4J; "
657 "defined where %%b is.\n"
659 " -> %%d: date (UNIX-like epoch)\n"
660 " -> %%r: application age (time elapsed since the beginning of the application)\n"
663 " --help-log-categories Display the current hierarchy of log categories.\n"
664 " --log=no_loc Don't print file names in messages (for tesh tests).\n"
668 static int xbt_log_cat_cmp(const void *pa, const void *pb)
670 xbt_log_category_t a = *(xbt_log_category_t *)pa;
671 xbt_log_category_t b = *(xbt_log_category_t *)pb;
672 return strcmp(a->name, b->name);
675 static void xbt_log_help_categories_rec(xbt_log_category_t category, const char *prefix)
680 xbt_log_category_t cat;
685 if (category->parent) {
686 this_prefix = bprintf("%s \\_ ", prefix);
687 child_prefix = bprintf("%s | ", prefix);
689 this_prefix = xbt_strdup(prefix);
690 child_prefix = xbt_strdup(prefix);
693 xbt_dynar_t dynar = xbt_dynar_new(sizeof(xbt_log_category_t), nullptr);
694 for (cat = category; cat != nullptr; cat = cat->nextSibling)
695 xbt_dynar_push_as(dynar, xbt_log_category_t, cat);
697 xbt_dynar_sort(dynar, xbt_log_cat_cmp);
699 xbt_dynar_foreach(dynar, i, cat){
700 if (i == xbt_dynar_length(dynar) - 1 && category->parent)
701 *strrchr(child_prefix, '|') = ' ';
702 printf("%s%s: %s\n", this_prefix, cat->name, cat->description);
703 xbt_log_help_categories_rec(cat->firstChild, child_prefix);
706 xbt_dynar_free(&dynar);
707 xbt_free(this_prefix);
708 xbt_free(child_prefix);
711 static void xbt_log_help_categories(void)
713 printf("Current log category hierarchy:\n");
714 xbt_log_help_categories_rec(&_XBT_LOGV(XBT_LOG_ROOT_CAT), " ");