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"
17 int xbt_log_no_loc = 0; /* if set to true (with --log=no_loc), file localization will be omitted (for tesh tests) */
18 static std::recursive_mutex* log_cat_init_mutex = nullptr;
20 /** @addtogroup XBT_log
22 * For more information, please refer to @ref outcomes_logs Section.
25 xbt_log_appender_t xbt_log_default_appender = nullptr; /* set in log_init */
26 xbt_log_layout_t xbt_log_default_layout = nullptr; /* set in log_init */
31 e_xbt_log_priority_t thresh;
33 xbt_log_appender_t appender;
34 } s_xbt_log_setting_t;
36 typedef s_xbt_log_setting_t* xbt_log_setting_t;
38 static xbt_dynar_t xbt_log_settings = nullptr;
40 static void _free_setting(void *s)
42 xbt_log_setting_t set = *(xbt_log_setting_t *) s;
44 xbt_free(set->catname);
50 static void _xbt_log_cat_apply_set(xbt_log_category_t category, xbt_log_setting_t setting);
52 const char *xbt_log_priority_names[8] = {
63 s_xbt_log_category_t _XBT_LOGV(XBT_LOG_ROOT_CAT) = {
65 nullptr /* firstChild */,
66 nullptr /* nextSibling */,
68 "The common ancestor for all categories",
70 xbt_log_priority_uninitialized /* threshold */,
71 0 /* isThreshInherited */,
72 nullptr /* appender */,
77 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(log, xbt, "Loggings from the logging mechanism itself");
79 /* create the default appender and install it in the root category,
80 which were already created (damnit. Too slow little beetle) */
81 void xbt_log_preinit(void)
83 xbt_log_default_appender = xbt_log_appender_file_new(nullptr);
84 xbt_log_default_layout = xbt_log_layout_simple_new(nullptr);
85 _XBT_LOGV(XBT_LOG_ROOT_CAT).appender = xbt_log_default_appender;
86 _XBT_LOGV(XBT_LOG_ROOT_CAT).layout = xbt_log_default_layout;
87 log_cat_init_mutex = new std::recursive_mutex();
90 static void xbt_log_help(void);
91 static void xbt_log_help_categories(void);
93 /** @brief Get all logging settings from the command line
95 * xbt_log_control_set() is called on each string we got from cmd line
97 void xbt_log_init(int *argc, char **argv)
99 unsigned help_requested = 0; /* 1: logs; 2: categories */
101 int parse_args = 1; // Stop parsing the parameters once we found '--'
103 /* Set logs and init log submodule */
104 for (int i = 1; i < *argc; i++) {
105 if (!strcmp("--", argv[i])) {
107 argv[j++] = argv[i]; // Keep the '--' for sg_config
108 } else if (parse_args && !strncmp(argv[i], "--log=", strlen("--log="))) {
109 char* opt = strchr(argv[i], '=');
111 xbt_log_control_set(opt);
112 XBT_DEBUG("Did apply '%s' as log setting", opt);
113 } else if (parse_args && !strcmp(argv[i], "--help-logs")) {
114 help_requested |= 1U;
115 } else if (parse_args && !strcmp(argv[i], "--help-log-categories")) {
116 help_requested |= 2U;
126 if (help_requested) {
127 if (help_requested & 1)
129 if (help_requested & 2)
130 xbt_log_help_categories();
135 static void log_cat_exit(xbt_log_category_t cat)
137 xbt_log_category_t child;
140 if (cat->appender->free_)
141 cat->appender->free_(cat->appender);
142 xbt_free(cat->appender);
145 if (cat->layout->free_)
146 cat->layout->free_(cat->layout);
147 xbt_free(cat->layout);
150 for (child = cat->firstChild; child != nullptr; child = child->nextSibling)
154 void xbt_log_postexit(void)
156 XBT_VERB("Exiting log");
157 delete log_cat_init_mutex;
158 xbt_dynar_free(&xbt_log_settings);
159 log_cat_exit(&_XBT_LOGV(XBT_LOG_ROOT_CAT));
162 /* Size of the static string in which we build the log string */
163 static constexpr size_t XBT_LOG_STATIC_BUFFER_SIZE = 2048;
164 /* Minimum size of the dynamic string in which we build the log string
165 (should be greater than XBT_LOG_STATIC_BUFFER_SIZE) */
166 static constexpr size_t XBT_LOG_DYNAMIC_BUFFER_SIZE = 4096;
168 void _xbt_log_event_log(xbt_log_event_t ev, const char *fmt, ...)
170 xbt_log_category_t cat = ev->cat;
172 xbt_assert(ev->priority >= 0, "Negative logging priority naturally forbidden");
173 xbt_assert(static_cast<size_t>(ev->priority) < sizeof(xbt_log_priority_names)/sizeof(xbt_log_priority_names[0]),
174 "Priority %d is greater than the biggest allowed value", ev->priority);
177 xbt_log_appender_t appender = cat->appender;
179 if (appender != nullptr) {
180 xbt_assert(cat->layout, "No valid layout for the appender of category %s", cat->name);
182 /* First, try with a static buffer */
184 char buff[XBT_LOG_STATIC_BUFFER_SIZE];
186 ev->buffer_size = sizeof buff;
187 va_start(ev->ap, fmt);
188 done = cat->layout->do_layout(cat->layout, ev, fmt);
191 appender->do_append(appender, buff);
194 /* The static buffer was too small, use a dynamically expanded one */
195 ev->buffer_size = XBT_LOG_DYNAMIC_BUFFER_SIZE;
196 ev->buffer = static_cast<char*>(xbt_malloc(ev->buffer_size));
198 va_start(ev->ap, fmt);
199 done = cat->layout->do_layout(cat->layout, ev, fmt);
203 ev->buffer_size *= 2;
204 ev->buffer = static_cast<char*>(xbt_realloc(ev->buffer, ev->buffer_size));
206 appender->do_append(appender, ev->buffer);
207 xbt_free(ev->buffer);
211 if (!cat->additivity)
219 * The standard logging macros use _XBT_LOG_ISENABLED, which calls _xbt_log_cat_init(). Thus, if we want to avoid an
220 * infinite recursion, we can not use the standard logging macros in _xbt_log_cat_init(), and in all functions called
223 * To circumvent the problem, we define the macro DISABLE_XBT_LOG_CAT_INIT() to hide the real _xbt_log_cat_init(). The
224 * macro has to be called at the beginning of the affected functions.
226 static int fake_xbt_log_cat_init(xbt_log_category_t, e_xbt_log_priority_t)
230 #define DISABLE_XBT_LOG_CAT_INIT() \
231 int (*_xbt_log_cat_init)(xbt_log_category_t, e_xbt_log_priority_t) XBT_ATTRIB_UNUSED = fake_xbt_log_cat_init;
233 static void _xbt_log_cat_apply_set(xbt_log_category_t category, xbt_log_setting_t setting)
235 DISABLE_XBT_LOG_CAT_INIT();
236 if (setting->thresh != xbt_log_priority_uninitialized) {
237 xbt_log_threshold_set(category, setting->thresh);
239 XBT_DEBUG("Apply settings for category '%s': set threshold to %s (=%d)",
240 category->name, xbt_log_priority_names[category->threshold], category->threshold);
244 xbt_log_layout_set(category, xbt_log_layout_format_new(setting->fmt));
246 XBT_DEBUG("Apply settings for category '%s': set format to %s", category->name, setting->fmt);
249 if (setting->additivity != -1) {
250 xbt_log_additivity_set(category, setting->additivity);
252 XBT_DEBUG("Apply settings for category '%s': set additivity to %s",
253 category->name, (setting->additivity ? "on" : "off"));
255 if (setting->appender) {
256 xbt_log_appender_set(category, setting->appender);
257 if (!category->layout)
258 xbt_log_layout_set(category, xbt_log_layout_simple_new(nullptr));
259 category->additivity = 0;
260 XBT_DEBUG("Set %p as appender of category '%s'", setting->appender, category->name);
265 * This gets called the first time a category is referenced and performs the initialization.
266 * Also resets threshold to inherited!
268 int _xbt_log_cat_init(xbt_log_category_t category, e_xbt_log_priority_t priority)
270 DISABLE_XBT_LOG_CAT_INIT();
271 if (category->initialized)
272 return priority >= category->threshold;
274 if (log_cat_init_mutex != nullptr)
275 log_cat_init_mutex->lock();
278 xbt_log_setting_t setting = nullptr;
280 XBT_DEBUG("Initializing category '%s' (firstChild=%s, nextSibling=%s)", category->name,
281 (category->firstChild ? category->firstChild->name : "none"),
282 (category->nextSibling ? category->nextSibling->name : "none"));
284 if (category == &_XBT_LOGV(XBT_LOG_ROOT_CAT)) {
285 category->threshold = xbt_log_priority_info;
286 category->appender = xbt_log_default_appender;
287 category->layout = xbt_log_default_layout;
289 if (!category->parent)
290 category->parent = &_XBT_LOGV(XBT_LOG_ROOT_CAT);
292 XBT_DEBUG("Set %s (%s) as father of %s ", category->parent->name,
293 (category->parent->initialized ? xbt_log_priority_names[category->parent->threshold] : "uninited"),
295 xbt_log_parent_set(category, category->parent);
297 if (XBT_LOG_ISENABLED(log, xbt_log_priority_debug)) {
299 xbt_log_category_t cpp = category->parent->firstChild;
301 res += std::string(" ") + cpp->name;
302 cpp = cpp->nextSibling;
305 XBT_DEBUG("Children of %s:%s; nextSibling: %s", category->parent->name, res.c_str(),
306 (category->parent->nextSibling ? category->parent->nextSibling->name : "none"));
310 /* Apply the control */
311 if (xbt_log_settings) {
312 xbt_assert(category, "NULL category");
313 xbt_assert(category->name);
316 xbt_dynar_foreach(xbt_log_settings, cursor, setting) {
317 xbt_assert(setting, "Damnit, NULL cat in the list");
318 xbt_assert(setting->catname, "NULL setting(=%p)->catname", (void *) setting);
320 if (!strcmp(setting->catname, category->name)) {
322 _xbt_log_cat_apply_set(category, setting);
323 xbt_dynar_cursor_rm(xbt_log_settings, &cursor);
328 XBT_DEBUG("Category '%s': inherited threshold = %s (=%d)",
329 category->name, xbt_log_priority_names[category->threshold], category->threshold);
332 category->initialized = 1;
333 if (log_cat_init_mutex != nullptr)
334 log_cat_init_mutex->unlock();
335 return priority >= category->threshold;
338 void xbt_log_parent_set(xbt_log_category_t cat, xbt_log_category_t parent)
340 xbt_assert(cat, "NULL category to be given a parent");
341 xbt_assert(parent, "The parent category of %s is NULL", cat->name);
343 /* if the category is initialized, unlink from current parent */
344 if (cat->initialized) {
345 xbt_log_category_t *cpp = &cat->parent->firstChild;
347 while (*cpp != cat && *cpp != nullptr) {
348 cpp = &(*cpp)->nextSibling;
351 xbt_assert(*cpp == cat);
352 *cpp = cat->nextSibling;
355 cat->parent = parent;
356 cat->nextSibling = parent->firstChild;
358 parent->firstChild = cat;
360 if (!parent->initialized)
361 _xbt_log_cat_init(parent, xbt_log_priority_uninitialized /* ignored */ );
363 cat->threshold = parent->threshold;
365 cat->isThreshInherited = 1;
368 static void _set_inherited_thresholds(xbt_log_category_t cat)
370 xbt_log_category_t child = cat->firstChild;
372 for (; child != nullptr; child = child->nextSibling) {
373 if (child->isThreshInherited) {
374 if (cat != &_XBT_LOGV(log))
375 XBT_VERB("Set category threshold of %s to %s (=%d)",
376 child->name, xbt_log_priority_names[cat->threshold], cat->threshold);
377 child->threshold = cat->threshold;
378 _set_inherited_thresholds(child);
383 void xbt_log_threshold_set(xbt_log_category_t cat, e_xbt_log_priority_t threshold)
385 cat->threshold = threshold;
386 cat->isThreshInherited = 0;
388 _set_inherited_thresholds(cat);
391 static xbt_log_setting_t _xbt_log_parse_setting(const char *control_string)
393 const char *orig_control_string = control_string;
394 xbt_log_setting_t set = xbt_new(s_xbt_log_setting_t, 1);
396 set->catname = nullptr;
397 set->thresh = xbt_log_priority_uninitialized;
399 set->additivity = -1;
400 set->appender = nullptr;
402 if (!*control_string)
404 XBT_DEBUG("Parse log setting '%s'", control_string);
406 control_string += strspn(control_string, " ");
407 const char *name = control_string;
408 control_string += strcspn(control_string, ".:= ");
409 const char *dot = control_string;
410 control_string += strcspn(control_string, ":= ");
411 const char *eq = control_string;
413 xbt_assert(*dot == '.' || (*eq != '=' && *eq != ':'), "Invalid control string '%s'", orig_control_string);
415 if (!strncmp(dot + 1, "threshold", (size_t) (eq - dot - 1))) {
417 char *neweq = xbt_strdup(eq + 1);
420 while (*(++p) != '\0') {
421 if (*p >= 'a' && *p <= 'z') {
426 XBT_DEBUG("New priority name = %s", neweq);
427 for (i = 0; i < xbt_log_priority_infinite; i++) {
428 if (!strncmp(xbt_log_priority_names[i], neweq, p - eq)) {
429 XBT_DEBUG("This is priority %d", i);
434 if(i<XBT_LOG_STATIC_THRESHOLD){
436 "Priority '%s' (in setting '%s') is above allowed priority '%s'.\n\n"
437 "Compiling SimGrid with -DNDEBUG forbids the levels 'trace' and 'debug'\n"
438 "while -DNLOG forbids any logging, at any level.",
439 eq + 1, name, xbt_log_priority_names[XBT_LOG_STATIC_THRESHOLD]);
441 }else if (i < xbt_log_priority_infinite) {
442 set->thresh = (e_xbt_log_priority_t) i;
445 "Unknown priority name: %s (must be one of: trace,debug,verbose,info,warning,error,critical)", eq + 1);
448 } else if (!strncmp(dot + 1, "add", (size_t) (eq - dot - 1)) ||
449 !strncmp(dot + 1, "additivity", (size_t) (eq - dot - 1))) {
450 char *neweq = xbt_strdup(eq + 1);
453 while (*(++p) != '\0') {
454 if (*p >= 'a' && *p <= 'z') {
458 if (!strcmp(neweq, "ON") || !strcmp(neweq, "YES") || !strcmp(neweq, "1")) {
464 } else if (!strncmp(dot + 1, "app", (size_t) (eq - dot - 1)) ||
465 !strncmp(dot + 1, "appender", (size_t) (eq - dot - 1))) {
466 char *neweq = xbt_strdup(eq + 1);
468 if (!strncmp(neweq, "file:", 5)) {
469 set->appender = xbt_log_appender_file_new(neweq + 5);
470 }else if (!strncmp(neweq, "rollfile:", 9)) {
471 set->appender = xbt_log_appender2_file_new(neweq + 9,1);
472 }else if (!strncmp(neweq, "splitfile:", 10)) {
473 set->appender = xbt_log_appender2_file_new(neweq + 10,0);
475 THROWF(arg_error, 0, "Unknown appender log type: '%s'", neweq);
478 } else if (!strncmp(dot + 1, "fmt", (size_t) (eq - dot - 1))) {
479 set->fmt = xbt_strdup(eq + 1);
482 snprintf(buff, std::min<int>(512, eq - dot), "%s", dot + 1);
483 xbt_die("Unknown setting of the log category: '%s'", buff);
485 set->catname = (char *) xbt_malloc(dot - name + 1);
487 memcpy(set->catname, name, dot - name);
488 set->catname[dot - name] = '\0'; /* Just in case */
489 XBT_DEBUG("This is for cat '%s'", set->catname);
494 static xbt_log_category_t _xbt_log_cat_searchsub(xbt_log_category_t cat, char *name)
496 xbt_log_category_t child;
497 xbt_log_category_t res;
499 XBT_DEBUG("Search '%s' into '%s' (firstChild='%s'; nextSibling='%s')", name,
500 cat->name, (cat->firstChild ? cat->firstChild->name : "none"),
501 (cat->nextSibling ? cat->nextSibling->name : "none"));
502 if (!strcmp(cat->name, name))
505 for (child = cat->firstChild; child != nullptr; child = child->nextSibling) {
506 XBT_DEBUG("Dig into %s", child->name);
507 res = _xbt_log_cat_searchsub(child, name);
517 * @param control_string What to parse
519 * Typically passed a command-line argument. The string has the syntax:
521 * ( [category] "." [keyword] ":" value (" ")... )...
523 * where [category] is one the category names (see @ref XBT_log_cats for a complete list of the ones defined in the
524 * SimGrid library) and keyword is one of the following:
526 * - thres: category's threshold priority. Possible values:
527 * TRACE,DEBUG,VERBOSE,INFO,WARNING,ERROR,CRITICAL
528 * - add or additivity: whether the logging actions must be passed to the parent category.
529 * Possible values: 0, 1, no, yes, on, off.
530 * Default value: yes.
531 * - fmt: the format to use. See @ref log_use_conf_fmt for more information.
532 * - app or appender: the appender to use. See @ref log_use_conf_app for more information.
534 void xbt_log_control_set(const char *control_string)
536 xbt_log_setting_t set;
538 /* To split the string in commands, and the cursors */
539 xbt_dynar_t set_strings;
545 XBT_DEBUG("Parse log settings '%s'", control_string);
547 /* Special handling of no_loc request, which asks for any file localization to be omitted (for tesh runs) */
548 if (!strcmp(control_string, "no_loc")) {
552 /* some initialization if this is the first time that this get called */
553 if (xbt_log_settings == nullptr)
554 xbt_log_settings = xbt_dynar_new(sizeof(xbt_log_setting_t), _free_setting);
556 /* split the string, and remove empty entries */
557 set_strings = xbt_str_split_quoted(control_string);
559 if (xbt_dynar_is_empty(set_strings)) { /* vicious user! */
560 xbt_dynar_free(&set_strings);
564 /* Parse each entry and either use it right now (if the category was already created), or store it for further use */
565 xbt_dynar_foreach(set_strings, cpt, str) {
566 set = _xbt_log_parse_setting(str);
567 xbt_log_category_t cat = _xbt_log_cat_searchsub(&_XBT_LOGV(XBT_LOG_ROOT_CAT), set->catname);
570 XBT_DEBUG("Apply directly");
571 _xbt_log_cat_apply_set(cat, set);
572 _free_setting((void *) &set);
574 XBT_DEBUG("Store for further application");
575 XBT_DEBUG("push %p to the settings", (void *) set);
576 xbt_dynar_push(xbt_log_settings, &set);
579 xbt_dynar_free(&set_strings);
582 void xbt_log_appender_set(xbt_log_category_t cat, xbt_log_appender_t app)
585 if (cat->appender->free_)
586 cat->appender->free_(cat->appender);
587 xbt_free(cat->appender);
592 void xbt_log_layout_set(xbt_log_category_t cat, xbt_log_layout_t lay)
594 DISABLE_XBT_LOG_CAT_INIT();
595 if (!cat->appender) {
596 XBT_VERB ("No appender to category %s. Setting the file appender as default", cat->name);
597 xbt_log_appender_set(cat, xbt_log_appender_file_new(nullptr));
600 if (cat->layout->free_) {
601 cat->layout->free_(cat->layout);
603 xbt_free(cat->layout);
606 xbt_log_additivity_set(cat, 0);
609 void xbt_log_additivity_set(xbt_log_category_t cat, int additivity)
611 cat->additivity = additivity;
614 static void xbt_log_help(void)
616 printf("Description of the logging output:\n"
618 " Threshold configuration: --log=CATEGORY_NAME.thres:PRIORITY_LEVEL\n"
619 " CATEGORY_NAME: defined in code with function 'XBT_LOG_NEW_CATEGORY'\n"
620 " PRIORITY_LEVEL: the level to print (trace,debug,verbose,info,warning,error,critical)\n"
621 " -> trace: enter and return of some functions\n"
622 " -> debug: crufty output\n"
623 " -> verbose: verbose output for the user wanting more\n"
624 " -> info: output about the regular functioning\n"
625 " -> warning: minor issue encountered\n"
626 " -> error: issue encountered\n"
627 " -> critical: major issue encountered\n"
628 " The default priority level is 'info'.\n"
630 " Format configuration: --log=CATEGORY_NAME.fmt:FORMAT\n"
631 " FORMAT string may contain:\n"
632 " -> %%%%: the %% char\n"
633 " -> %%n: platform-dependent line separator (LOG4J compatible)\n"
634 " -> %%e: plain old space (SimGrid extension)\n"
636 " -> %%m: user-provided message\n"
638 " -> %%c: Category name (LOG4J compatible)\n"
639 " -> %%p: Priority name (LOG4J compatible)\n"
641 " -> %%h: Hostname (SimGrid extension)\n"
642 " -> %%P: Process name (SimGrid extension)\n"
643 " -> %%t: Thread \"name\" (LOG4J compatible -- actually the address of the thread in memory)\n"
644 " -> %%i: Process PID (SimGrid extension -- this is a 'i' as in 'i'dea)\n"
646 " -> %%F: file name where the log event was raised (LOG4J compatible)\n"
647 " -> %%l: location where the log event was raised (LOG4J compatible, like '%%F:%%L' -- this is a l as "
649 " -> %%L: line number where the log event was raised (LOG4J compatible)\n"
650 " -> %%M: function name (LOG4J compatible -- called method name here of course).\n"
651 " Defined only when using gcc because there is no __func__ elsewhere.\n"
653 " -> %%b: full backtrace (Called %%throwable in LOG4J). Defined only under windows or when using the "
655 " backtrace() is not defined elsewhere, and we only have a fallback for windows boxes, not "
656 "mac ones for example.\n"
657 " -> %%B: short backtrace (only the first line of the %%b). Called %%throwable{short} in LOG4J; "
658 "defined where %%b is.\n"
660 " -> %%d: date (UNIX-like epoch)\n"
661 " -> %%r: application age (time elapsed since the beginning of the application)\n"
664 " --help-log-categories Display the current hierarchy of log categories.\n"
665 " --log=no_loc Don't print file names in messages (for tesh tests).\n"
669 static int xbt_log_cat_cmp(const void *pa, const void *pb)
671 xbt_log_category_t a = *(xbt_log_category_t *)pa;
672 xbt_log_category_t b = *(xbt_log_category_t *)pb;
673 return strcmp(a->name, b->name);
676 static void xbt_log_help_categories_rec(xbt_log_category_t category, const char *prefix)
681 xbt_log_category_t cat;
686 if (category->parent) {
687 this_prefix = bprintf("%s \\_ ", prefix);
688 child_prefix = bprintf("%s | ", prefix);
690 this_prefix = xbt_strdup(prefix);
691 child_prefix = xbt_strdup(prefix);
694 xbt_dynar_t dynar = xbt_dynar_new(sizeof(xbt_log_category_t), nullptr);
695 for (cat = category; cat != nullptr; cat = cat->nextSibling)
696 xbt_dynar_push_as(dynar, xbt_log_category_t, cat);
698 xbt_dynar_sort(dynar, xbt_log_cat_cmp);
700 xbt_dynar_foreach(dynar, i, cat){
701 if (i == xbt_dynar_length(dynar) - 1 && category->parent)
702 *strrchr(child_prefix, '|') = ' ';
703 printf("%s%s: %s\n", this_prefix, cat->name, cat->description);
704 xbt_log_help_categories_rec(cat->firstChild, child_prefix);
707 xbt_dynar_free(&dynar);
708 xbt_free(this_prefix);
709 xbt_free(child_prefix);
712 static void xbt_log_help_categories(void)
714 printf("Current log category hierarchy:\n");
715 xbt_log_help_categories_rec(&_XBT_LOGV(XBT_LOG_ROOT_CAT), " ");