1 /* log - a generic logging facility in the spirit of log4j */
3 /* Copyright (c) 2004-2018. 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. */
10 #include <stdio.h> /* snprintf */
11 #include <stdlib.h> /* snprintf */
13 #include "src/internal_config.h"
15 #include "src/xbt_modinter.h"
17 #include "src/xbt/log_private.h"
18 #include "xbt/asserts.h"
19 #include "xbt/dynar.h"
23 #include "xbt/sysdep.h"
24 #include "xbt/xbt_os_thread.h"
27 #define MIN(a, b) ((a) < (b) ? (a) : (b))
30 #define MAX(a, b) ((a) > (b) ? (a) : (b))
33 int xbt_log_no_loc = 0; /* if set to true (with --log=no_loc), file localization will be omitted (for tesh tests) */
34 static xbt_os_mutex_t log_cat_init_mutex = NULL;
36 /** \addtogroup XBT_log
38 * For more information, please refer to @ref outcomes_logs Section.
41 xbt_log_appender_t xbt_log_default_appender = NULL; /* set in log_init */
42 xbt_log_layout_t xbt_log_default_layout = NULL; /* set in log_init */
47 e_xbt_log_priority_t thresh;
49 xbt_log_appender_t appender;
50 } s_xbt_log_setting_t;
52 typedef s_xbt_log_setting_t* xbt_log_setting_t;
54 static xbt_dynar_t xbt_log_settings = NULL;
56 static void _free_setting(void *s)
58 xbt_log_setting_t set = *(xbt_log_setting_t *) s;
66 static void _xbt_log_cat_apply_set(xbt_log_category_t category, xbt_log_setting_t setting);
68 const char *xbt_log_priority_names[8] = {
79 s_xbt_log_category_t _XBT_LOGV(XBT_LOG_ROOT_CAT) = {
80 NULL /*parent */ , NULL /* firstChild */ , NULL /* nextSibling */ ,
81 "root", "The common ancestor for all categories",
82 0 /*initialized */, xbt_log_priority_uninitialized /* threshold */ ,
83 0 /* isThreshInherited */ ,
84 NULL /* appender */ , NULL /* layout */ ,
88 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(log, xbt, "Loggings from the logging mechanism itself");
90 /* create the default appender and install it in the root category,
91 which were already created (damnit. Too slow little beetle) */
92 void xbt_log_preinit(void)
94 xbt_log_default_appender = xbt_log_appender_file_new(NULL);
95 xbt_log_default_layout = xbt_log_layout_simple_new(NULL);
96 _XBT_LOGV(XBT_LOG_ROOT_CAT).appender = xbt_log_default_appender;
97 _XBT_LOGV(XBT_LOG_ROOT_CAT).layout = xbt_log_default_layout;
98 log_cat_init_mutex = xbt_os_mutex_init();
101 static void xbt_log_help(void);
102 static void xbt_log_help_categories(void);
104 /** @brief Get all logging settings from the command line
106 * xbt_log_control_set() is called on each string we got from cmd line
108 void xbt_log_init(int *argc, char **argv)
110 unsigned help_requested = 0; /* 1: logs; 2: categories */
113 /* Set logs and init log submodule */
114 for (int i = 1; i < *argc; i++) {
115 if (!strncmp(argv[i], "--log=", strlen("--log="))) {
116 char* opt = strchr(argv[i], '=');
118 xbt_log_control_set(opt);
119 XBT_DEBUG("Did apply '%s' as log setting", opt);
120 } else if (!strcmp(argv[i], "--help-logs")) {
121 help_requested |= 1U;
122 } else if (!strcmp(argv[i], "--help-log-categories")) {
123 help_requested |= 2U;
133 if (help_requested) {
134 if (help_requested & 1)
136 if (help_requested & 2)
137 xbt_log_help_categories();
142 static void log_cat_exit(xbt_log_category_t cat)
144 xbt_log_category_t child;
147 if (cat->appender->free_)
148 cat->appender->free_(cat->appender);
152 if (cat->layout->free_)
153 cat->layout->free_(cat->layout);
157 for (child = cat->firstChild; child != NULL; child = child->nextSibling)
161 void xbt_log_postexit(void)
163 XBT_VERB("Exiting log");
164 xbt_os_mutex_destroy(log_cat_init_mutex);
165 xbt_dynar_free(&xbt_log_settings);
166 log_cat_exit(&_XBT_LOGV(XBT_LOG_ROOT_CAT));
169 /* Size of the static string in which we build the log string */
170 #define XBT_LOG_STATIC_BUFFER_SIZE 2048
171 /* Minimum size of the dynamic string in which we build the log string
172 (should be greater than XBT_LOG_STATIC_BUFFER_SIZE) */
173 #define XBT_LOG_DYNAMIC_BUFFER_SIZE 4096
175 void _xbt_log_event_log(xbt_log_event_t ev, const char *fmt, ...)
177 xbt_log_category_t cat = ev->cat;
179 xbt_assert(ev->priority >= 0, "Negative logging priority naturally forbidden");
180 xbt_assert(ev->priority < sizeof(xbt_log_priority_names), "Priority %d is greater than the biggest allowed value",
184 xbt_log_appender_t appender = cat->appender;
186 if (appender != NULL) {
187 xbt_assert(cat->layout, "No valid layout for the appender of category %s", cat->name);
189 /* First, try with a static buffer */
191 char buff[XBT_LOG_STATIC_BUFFER_SIZE];
193 ev->buffer_size = sizeof buff;
194 va_start(ev->ap, fmt);
195 done = cat->layout->do_layout(cat->layout, ev, fmt);
198 appender->do_append(appender, buff);
201 /* The static buffer was too small, use a dynamically expanded one */
202 ev->buffer_size = XBT_LOG_DYNAMIC_BUFFER_SIZE;
203 ev->buffer = xbt_malloc(ev->buffer_size);
205 va_start(ev->ap, fmt);
206 done = cat->layout->do_layout(cat->layout, ev, fmt);
210 ev->buffer_size *= 2;
211 ev->buffer = xbt_realloc(ev->buffer, ev->buffer_size);
213 appender->do_append(appender, ev->buffer);
214 xbt_free(ev->buffer);
218 if (!cat->additivity)
226 * The standard logging macros use _XBT_LOG_ISENABLED, which calls _xbt_log_cat_init(). Thus, if we want to avoid an
227 * infinite recursion, we can not use the standard logging macros in _xbt_log_cat_init(), and in all functions called
230 * To circumvent the problem, we define the macro DISABLE_XBT_LOG_CAT_INIT() to hide the real _xbt_log_cat_init(). The
231 * macro has to be called at the beginning of the affected functions.
233 static int fake_xbt_log_cat_init(xbt_log_category_t XBT_ATTRIB_UNUSED category,
234 e_xbt_log_priority_t XBT_ATTRIB_UNUSED priority)
238 #define DISABLE_XBT_LOG_CAT_INIT() \
239 int (*_xbt_log_cat_init)(xbt_log_category_t, e_xbt_log_priority_t) XBT_ATTRIB_UNUSED = fake_xbt_log_cat_init;
241 static void _xbt_log_cat_apply_set(xbt_log_category_t category, xbt_log_setting_t setting)
243 DISABLE_XBT_LOG_CAT_INIT();
244 if (setting->thresh != xbt_log_priority_uninitialized) {
245 xbt_log_threshold_set(category, setting->thresh);
247 XBT_DEBUG("Apply settings for category '%s': set threshold to %s (=%d)",
248 category->name, xbt_log_priority_names[category->threshold], category->threshold);
252 xbt_log_layout_set(category, xbt_log_layout_format_new(setting->fmt));
254 XBT_DEBUG("Apply settings for category '%s': set format to %s", category->name, setting->fmt);
257 if (setting->additivity != -1) {
258 xbt_log_additivity_set(category, setting->additivity);
260 XBT_DEBUG("Apply settings for category '%s': set additivity to %s",
261 category->name, (setting->additivity ? "on" : "off"));
263 if (setting->appender) {
264 xbt_log_appender_set(category, setting->appender);
265 if (!category->layout)
266 xbt_log_layout_set(category, xbt_log_layout_simple_new(NULL));
267 category->additivity = 0;
268 XBT_DEBUG("Set %p as appender of category '%s'", setting->appender, category->name);
273 * This gets called the first time a category is referenced and performs the initialization.
274 * Also resets threshold to inherited!
276 int _xbt_log_cat_init(xbt_log_category_t category, e_xbt_log_priority_t priority)
278 DISABLE_XBT_LOG_CAT_INIT();
279 if (log_cat_init_mutex != NULL)
280 xbt_os_mutex_acquire(log_cat_init_mutex);
282 if (category->initialized) {
283 if (log_cat_init_mutex != NULL)
284 xbt_os_mutex_release(log_cat_init_mutex);
285 return priority >= category->threshold;
289 xbt_log_setting_t setting = NULL;
291 XBT_DEBUG("Initializing category '%s' (firstChild=%s, nextSibling=%s)", category->name,
292 (category->firstChild ? category->firstChild->name : "none"),
293 (category->nextSibling ? category->nextSibling->name : "none"));
295 if (category == &_XBT_LOGV(XBT_LOG_ROOT_CAT)) {
296 category->threshold = xbt_log_priority_info;
297 category->appender = xbt_log_default_appender;
298 category->layout = xbt_log_default_layout;
300 if (!category->parent)
301 category->parent = &_XBT_LOGV(XBT_LOG_ROOT_CAT);
303 XBT_DEBUG("Set %s (%s) as father of %s ", category->parent->name,
304 (category->parent->initialized ? xbt_log_priority_names[category->parent->threshold] : "uninited"),
306 xbt_log_parent_set(category, category->parent);
308 if (XBT_LOG_ISENABLED(log, xbt_log_priority_debug)) {
311 xbt_log_category_t cpp = category->parent->firstChild;
314 buf = bprintf("%s %s", res, cpp->name);
318 res = xbt_strdup(cpp->name);
320 cpp = cpp->nextSibling;
323 XBT_DEBUG("Children of %s: %s; nextSibling: %s", category->parent->name, res,
324 (category->parent->nextSibling ? category->parent->nextSibling->name : "none"));
330 /* Apply the control */
331 if (xbt_log_settings) {
332 xbt_assert(category, "NULL category");
333 xbt_assert(category->name);
336 xbt_dynar_foreach(xbt_log_settings, cursor, setting) {
337 xbt_assert(setting, "Damnit, NULL cat in the list");
338 xbt_assert(setting->catname, "NULL setting(=%p)->catname", (void *) setting);
340 if (!strcmp(setting->catname, category->name)) {
342 _xbt_log_cat_apply_set(category, setting);
343 xbt_dynar_cursor_rm(xbt_log_settings, &cursor);
348 XBT_DEBUG("Category '%s': inherited threshold = %s (=%d)",
349 category->name, xbt_log_priority_names[category->threshold], category->threshold);
352 category->initialized = 1;
353 if (log_cat_init_mutex != NULL)
354 xbt_os_mutex_release(log_cat_init_mutex);
355 return priority >= category->threshold;
358 void xbt_log_parent_set(xbt_log_category_t cat, xbt_log_category_t parent)
360 xbt_assert(cat, "NULL category to be given a parent");
361 xbt_assert(parent, "The parent category of %s is NULL", cat->name);
363 /* if the category is initialized, unlink from current parent */
364 if (cat->initialized) {
365 xbt_log_category_t *cpp = &cat->parent->firstChild;
367 while (*cpp != cat && *cpp != NULL) {
368 cpp = &(*cpp)->nextSibling;
371 xbt_assert(*cpp == cat);
372 *cpp = cat->nextSibling;
375 cat->parent = parent;
376 cat->nextSibling = parent->firstChild;
378 parent->firstChild = cat;
380 if (!parent->initialized)
381 _xbt_log_cat_init(parent, xbt_log_priority_uninitialized /* ignored */ );
383 cat->threshold = parent->threshold;
385 cat->isThreshInherited = 1;
388 static void _set_inherited_thresholds(xbt_log_category_t cat)
390 xbt_log_category_t child = cat->firstChild;
392 for (; child != NULL; child = child->nextSibling) {
393 if (child->isThreshInherited) {
394 if (cat != &_XBT_LOGV(log))
395 XBT_VERB("Set category threshold of %s to %s (=%d)",
396 child->name, xbt_log_priority_names[cat->threshold], cat->threshold);
397 child->threshold = cat->threshold;
398 _set_inherited_thresholds(child);
403 void xbt_log_threshold_set(xbt_log_category_t cat, e_xbt_log_priority_t threshold)
405 cat->threshold = threshold;
406 cat->isThreshInherited = 0;
408 _set_inherited_thresholds(cat);
411 static xbt_log_setting_t _xbt_log_parse_setting(const char *control_string)
413 const char *orig_control_string = control_string;
414 xbt_log_setting_t set = xbt_new(s_xbt_log_setting_t, 1);
417 set->thresh = xbt_log_priority_uninitialized;
419 set->additivity = -1;
420 set->appender = NULL;
422 if (!*control_string)
424 XBT_DEBUG("Parse log setting '%s'", control_string);
426 control_string += strspn(control_string, " ");
427 const char *name = control_string;
428 control_string += strcspn(control_string, ".:= ");
429 const char *dot = control_string;
430 control_string += strcspn(control_string, ":= ");
431 const char *eq = control_string;
433 xbt_assert(*dot == '.' || (*eq != '=' && *eq != ':'), "Invalid control string '%s'", orig_control_string);
435 if (!strncmp(dot + 1, "threshold", (size_t) (eq - dot - 1))) {
437 char *neweq = xbt_strdup(eq + 1);
440 while (*(++p) != '\0') {
441 if (*p >= 'a' && *p <= 'z') {
446 XBT_DEBUG("New priority name = %s", neweq);
447 for (i = 0; i < xbt_log_priority_infinite; i++) {
448 if (!strncmp(xbt_log_priority_names[i], neweq, p - eq)) {
449 XBT_DEBUG("This is priority %d", i);
454 if(i<XBT_LOG_STATIC_THRESHOLD){
456 "Priority '%s' (in setting '%s') is above allowed priority '%s'.\n\n"
457 "Compiling SimGrid with -DNDEBUG forbids the levels 'trace' and 'debug'\n"
458 "while -DNLOG forbids any logging, at any level.",
459 eq + 1, name, xbt_log_priority_names[XBT_LOG_STATIC_THRESHOLD]);
461 }else if (i < xbt_log_priority_infinite) {
462 set->thresh = (e_xbt_log_priority_t) i;
465 "Unknown priority name: %s (must be one of: trace,debug,verbose,info,warning,error,critical)", eq + 1);
468 } else if (!strncmp(dot + 1, "add", (size_t) (eq - dot - 1)) ||
469 !strncmp(dot + 1, "additivity", (size_t) (eq - dot - 1))) {
470 char *neweq = xbt_strdup(eq + 1);
473 while (*(++p) != '\0') {
474 if (*p >= 'a' && *p <= 'z') {
478 if (!strcmp(neweq, "ON") || !strcmp(neweq, "YES") || !strcmp(neweq, "1")) {
484 } else if (!strncmp(dot + 1, "app", (size_t) (eq - dot - 1)) ||
485 !strncmp(dot + 1, "appender", (size_t) (eq - dot - 1))) {
486 char *neweq = xbt_strdup(eq + 1);
488 if (!strncmp(neweq, "file:", 5)) {
489 set->appender = xbt_log_appender_file_new(neweq + 5);
490 }else if (!strncmp(neweq, "rollfile:", 9)) {
491 set->appender = xbt_log_appender2_file_new(neweq + 9,1);
492 }else if (!strncmp(neweq, "splitfile:", 10)) {
493 set->appender = xbt_log_appender2_file_new(neweq + 10,0);
495 THROWF(arg_error, 0, "Unknown appender log type: '%s'", neweq);
498 } else if (!strncmp(dot + 1, "fmt", (size_t) (eq - dot - 1))) {
499 set->fmt = xbt_strdup(eq + 1);
502 snprintf(buff, MIN(512, eq - dot), "%s", dot + 1);
503 xbt_die("Unknown setting of the log category: '%s'", buff);
505 set->catname = (char *) xbt_malloc(dot - name + 1);
507 memcpy(set->catname, name, dot - name);
508 set->catname[dot - name] = '\0'; /* Just in case */
509 XBT_DEBUG("This is for cat '%s'", set->catname);
514 static xbt_log_category_t _xbt_log_cat_searchsub(xbt_log_category_t cat, char *name)
516 xbt_log_category_t child;
517 xbt_log_category_t res;
519 XBT_DEBUG("Search '%s' into '%s' (firstChild='%s'; nextSibling='%s')", name,
520 cat->name, (cat->firstChild ? cat->firstChild->name : "none"),
521 (cat->nextSibling ? cat->nextSibling->name : "none"));
522 if (!strcmp(cat->name, name))
525 for (child = cat->firstChild; child != NULL; child = child->nextSibling) {
526 XBT_DEBUG("Dig into %s", child->name);
527 res = _xbt_log_cat_searchsub(child, name);
537 * \param control_string What to parse
539 * Typically passed a command-line argument. The string has the syntax:
541 * ( [category] "." [keyword] ":" value (" ")... )...
543 * where [category] is one the category names (see \ref XBT_log_cats for a complete list of the ones defined in the
544 * SimGrid library) and keyword is one of the following:
546 * - thres: category's threshold priority. Possible values:
547 * TRACE,DEBUG,VERBOSE,INFO,WARNING,ERROR,CRITICAL
548 * - add or additivity: whether the logging actions must be passed to the parent category.
549 * Possible values: 0, 1, no, yes, on, off.
550 * Default value: yes.
551 * - fmt: the format to use. See \ref log_use_conf_fmt for more information.
552 * - app or appender: the appender to use. See \ref log_use_conf_app for more information.
554 void xbt_log_control_set(const char *control_string)
556 xbt_log_setting_t set;
558 /* To split the string in commands, and the cursors */
559 xbt_dynar_t set_strings;
565 XBT_DEBUG("Parse log settings '%s'", control_string);
567 /* Special handling of no_loc request, which asks for any file localization to be omitted (for tesh runs) */
568 if (!strcmp(control_string, "no_loc")) {
572 /* some initialization if this is the first time that this get called */
573 if (xbt_log_settings == NULL)
574 xbt_log_settings = xbt_dynar_new(sizeof(xbt_log_setting_t), _free_setting);
576 /* split the string, and remove empty entries */
577 set_strings = xbt_str_split_quoted(control_string);
579 if (xbt_dynar_is_empty(set_strings)) { /* vicious user! */
580 xbt_dynar_free(&set_strings);
584 /* Parse each entry and either use it right now (if the category was already created), or store it for further use */
585 xbt_dynar_foreach(set_strings, cpt, str) {
586 set = _xbt_log_parse_setting(str);
587 xbt_log_category_t cat = _xbt_log_cat_searchsub(&_XBT_LOGV(XBT_LOG_ROOT_CAT), set->catname);
590 XBT_DEBUG("Apply directly");
591 _xbt_log_cat_apply_set(cat, set);
592 _free_setting((void *) &set);
594 XBT_DEBUG("Store for further application");
595 XBT_DEBUG("push %p to the settings", (void *) set);
596 xbt_dynar_push(xbt_log_settings, &set);
599 xbt_dynar_free(&set_strings);
602 void xbt_log_appender_set(xbt_log_category_t cat, xbt_log_appender_t app)
605 if (cat->appender->free_)
606 cat->appender->free_(cat->appender);
612 void xbt_log_layout_set(xbt_log_category_t cat, xbt_log_layout_t lay)
614 DISABLE_XBT_LOG_CAT_INIT();
615 if (!cat->appender) {
616 XBT_VERB ("No appender to category %s. Setting the file appender as default", cat->name);
617 xbt_log_appender_set(cat, xbt_log_appender_file_new(NULL));
620 if (cat->layout->free_) {
621 cat->layout->free_(cat->layout);
626 xbt_log_additivity_set(cat, 0);
629 void xbt_log_additivity_set(xbt_log_category_t cat, int additivity)
631 cat->additivity = additivity;
634 static void xbt_log_help(void)
636 printf("Description of the logging output:\n"
638 " Threshold configuration: --log=CATEGORY_NAME.thres:PRIORITY_LEVEL\n"
639 " CATEGORY_NAME: defined in code with function 'XBT_LOG_NEW_CATEGORY'\n"
640 " PRIORITY_LEVEL: the level to print (trace,debug,verbose,info,warning,error,critical)\n"
641 " -> trace: enter and return of some functions\n"
642 " -> debug: crufty output\n"
643 " -> verbose: verbose output for the user wanting more\n"
644 " -> info: output about the regular functioning\n"
645 " -> warning: minor issue encountered\n"
646 " -> error: issue encountered\n"
647 " -> critical: major issue encountered\n"
648 " The default priority level is 'info'.\n"
650 " Format configuration: --log=CATEGORY_NAME.fmt:FORMAT\n"
651 " FORMAT string may contain:\n"
652 " -> %%%%: the %% char\n"
653 " -> %%n: platform-dependent line separator (LOG4J compatible)\n"
654 " -> %%e: plain old space (SimGrid extension)\n"
656 " -> %%m: user-provided message\n"
658 " -> %%c: Category name (LOG4J compatible)\n"
659 " -> %%p: Priority name (LOG4J compatible)\n"
661 " -> %%h: Hostname (SimGrid extension)\n"
662 " -> %%P: Process name (SimGrid extension)\n"
663 " -> %%t: Thread \"name\" (LOG4J compatible -- actually the address of the thread in memory)\n"
664 " -> %%i: Process PID (SimGrid extension -- this is a 'i' as in 'i'dea)\n"
666 " -> %%F: file name where the log event was raised (LOG4J compatible)\n"
667 " -> %%l: location where the log event was raised (LOG4J compatible, like '%%F:%%L' -- this is a l as "
669 " -> %%L: line number where the log event was raised (LOG4J compatible)\n"
670 " -> %%M: function name (LOG4J compatible -- called method name here of course).\n"
671 " Defined only when using gcc because there is no __func__ elsewhere.\n"
673 " -> %%b: full backtrace (Called %%throwable in LOG4J). Defined only under windows or when using the "
675 " backtrace() is not defined elsewhere, and we only have a fallback for windows boxes, not "
676 "mac ones for example.\n"
677 " -> %%B: short backtrace (only the first line of the %%b). Called %%throwable{short} in LOG4J; "
678 "defined where %%b is.\n"
680 " -> %%d: date (UNIX-like epoch)\n"
681 " -> %%r: application age (time elapsed since the beginning of the application)\n"
684 " --help-log-categories Display the current hierarchy of log categories.\n"
685 " --log=no_loc Don't print file names in messages (for tesh tests).\n"
689 static int xbt_log_cat_cmp(const void *pa, const void *pb)
691 xbt_log_category_t a = *(xbt_log_category_t *)pa;
692 xbt_log_category_t b = *(xbt_log_category_t *)pb;
693 return strcmp(a->name, b->name);
696 static void xbt_log_help_categories_rec(xbt_log_category_t category, const char *prefix)
701 xbt_log_category_t cat;
706 if (category->parent) {
707 this_prefix = bprintf("%s \\_ ", prefix);
708 child_prefix = bprintf("%s | ", prefix);
710 this_prefix = xbt_strdup(prefix);
711 child_prefix = xbt_strdup(prefix);
714 xbt_dynar_t dynar = xbt_dynar_new(sizeof(xbt_log_category_t), NULL);
715 for (cat = category ; cat != NULL; cat = cat->nextSibling)
716 xbt_dynar_push_as(dynar, xbt_log_category_t, cat);
718 xbt_dynar_sort(dynar, xbt_log_cat_cmp);
720 xbt_dynar_foreach(dynar, i, cat){
721 if (i == xbt_dynar_length(dynar) - 1 && category->parent)
722 *strrchr(child_prefix, '|') = ' ';
723 printf("%s%s: %s\n", this_prefix, cat->name, cat->description);
724 xbt_log_help_categories_rec(cat->firstChild, child_prefix);
727 xbt_dynar_free(&dynar);
728 xbt_free(this_prefix);
729 xbt_free(child_prefix);
732 static void xbt_log_help_categories(void)
734 printf("Current log category hierarchy:\n");
735 xbt_log_help_categories_rec(&_XBT_LOGV(XBT_LOG_ROOT_CAT), " ");