3 /* log - a generic logging facility in the spirit of log4j */
5 /* Copyright (c) 2003, 2004 Martin Quinson. All rights reserved. */
7 /* This program is free software; you can redistribute it and/or modify it
8 * under the terms of the license (GNU LGPL) which comes with this package. */
13 #include <stdio.h> /* snprintf */
14 #include <stdlib.h> /* snprintf */
15 #include "gras_config.h" /* to get a working stdarg.h */
17 #include "xbt_modinter.h"
21 #include "xbt/sysdep.h"
23 #include "xbt/dynar.h"
25 /** \addtogroup XBT_log
27 * This section describes the API to the log functions used
28 * everywhere in this project.
30 \section XBT_log_toc Table of contents
42 - \ref log_API_example
50 \section log_overview 1. Introduction
52 This module is in charge of handling the log messages of every SimGrid
53 program. The main design goal are:
55 - <b>configurability</b>: the user can choose <i>at runtime</i> what messages to show and
56 what to hide, as well as how messages get displayed.
57 - <b>ease of use</b>: both to the programmer (using preprocessor macros black magic)
58 and to the user (with command line options)
59 - <b>performances</b>: logging shouldn't slow down the program when turned off, for example
60 - deal with <b>distributed settings</b>: SimGrid programs are [often] distributed ones,
61 and the logging mecanism allows to syndicate each and every log source into the same place.
62 At least, its design would allow to, once we write the last missing pieces
64 There is three main concepts in SimGrid's logging mecanism: <i>category</i>,
65 <i>priority</i> and <i>appender</i>. These three concepts work together to
66 enable developers to log messages according to message type and priority, and
67 to control at runtime how these messages are formatted and where they are
70 \subsection log_cat 1.1 Category hierarchy
72 The first and foremost advantage of any logging API over plain printf()
73 resides in its ability to disable certain log statements while allowing
74 others to print unhindered. This capability assumes that the logging space,
75 that is, the space of all possible logging statements, is categorized
76 according to some developer-chosen criteria.
78 This observation led to choosing category as the central concept of the
79 system. In a certain sense, they can be considered as logging topics or
82 \subsection log_pri 1.2 Logging priorities
84 The user can naturally declare interest into this or that logging category, but
85 he also can specify the desired level of details for each of them. This is
86 controled by the <i>priority</i> concept (which should maybe be renamed to
89 Empirically, the user can specify that he wants to see every debuging message
90 of GRAS while only being interested into the messages at level "error" or
91 higher about the XBT internals.
93 \subsection log_app 1.3 Message appenders
95 The message appenders are the elements in charge of actually displaying the
96 message to the user. For now, there is only one appender: the one able to print
97 stuff on stderr. But everything is in place internally to write new ones, such
98 as the one able to send the strings to a central server in charge of
99 syndicating the logs of every distributed daemons on a well known location.
101 It should also be possible to pass configuration informations to the appenders,
102 specifying for example that the message location (file and line number) is only
103 relevant to debugging information, not to critical error messages.
107 \subsection log_hist 1.4 History of this module
109 Historically, this module is an adaptation of the log4c project, which is dead
110 upstream, and which I was given the permission to fork under the LGPL licence
111 by the log4c's authors. The log4c project itself was loosely based on the
112 Apache project's Log4J, which also inspired Log4CC, Log4py and so on. Our work
113 differs somehow from these projects anyway, because the C programming language
114 is not object oriented.
116 \section log_API 2. Programmer interface
118 \subsection log_API_cat 2.1 Constructing the category hierarchy
120 Every category is declared by providing a name and an optional
121 parent. If no parent is explicitly named, the root category, LOG_ROOT_CAT is
122 the category's parent.
124 A category is created by a macro call at the top level of a file. A
125 category can be created with any one of the following macros:
127 - \ref XBT_LOG_NEW_CATEGORY(MyCat); Create a new root
128 - \ref XBT_LOG_NEW_SUBCATEGORY(MyCat, ParentCat);
129 Create a new category being child of the category ParentCat
130 - \ref XBT_LOG_NEW_DEFAULT_CATEGORY(MyCat);
131 Like XBT_LOG_NEW_CATEGORY, but the new category is the default one
133 - \ref XBT_LOG_NEW_DEFAULT_SUBCATEGORY(MyCat, ParentCat);
134 Like XBT_LOG_NEW_SUBCATEGORY, but the new category is the default one
137 The parent cat can be defined in the same file or in another file (in
138 which case you want to use the \ref XBT_LOG_EXTERNAL_CATEGORY macro to make
139 it visible in the current file), but each category may have only one
142 Typically, there will be a Category for each module and sub-module, so you
143 can independently control logging for each module.
145 For a list of all existing categories, please refer to the \ref XBT_log_cats
146 section. This file is generated automatically from the SimGrid source code, so
147 it should be complete and accurate.
149 \section log_API_pri 2.2 Declaring message priority
151 A category may be assigned a threshold priorty. The set of priorites are
152 defined by the \ref e_xbt_log_priority_t enum. All logging request under
153 this priority will be discarded.
155 If a given category is not assigned a threshold priority, then it inherits
156 one from its closest ancestor with an assigned threshold. To ensure that all
157 categories can eventually inherit a threshold, the root category always has
158 an assigned threshold priority.
160 Logging requests are made by invoking a logging macro on a category. All of
161 the macros have a printf-style format string followed by arguments. If you
162 compile with the -Wall option, gcc will warn you for unmatched arguments, ie
163 when you pass a pointer to a string where an integer was specified by the
164 format. This is usualy a good idea.
166 Because some C compilers do not support vararg macros, there is a version of
167 the macro for any number of arguments from 0 to 6. The macro name ends with
168 the total number of arguments.
170 Here is an example of the most basic type of macro. This is a logging
171 request with priority <i>warning</i>.
173 <code>CLOG5(MyCat, gras_log_priority_warning, "Values are: %d and '%s'", 5,
176 A logging request is said to be enabled if its priority is higher than or
177 equal to the threshold priority of its category. Otherwise, the request is
178 said to be disabled. A category without an assigned priority will inherit
179 one from the hierarchy.
181 It is possible to use any non-negative integer as a priority. If, as in the
182 example, one of the standard priorites is used, then there is a convenience
183 macro that is typically used instead. For example, the above example is
184 equivalent to the shorter:
186 <code>CWARN4(MyCat, "Values are: %d and '%s'", 5, "oops");</code>
188 \section log_API_subcat 2.3 Using a default category (the easy interface)
190 If \ref XBT_LOG_NEW_DEFAULT_SUBCATEGORY(MyCat, Parent) or
191 \ref XBT_LOG_NEW_DEFAULT_CATEGORY(MyCat) is used to create the
192 category, then the even shorter form can be used:
194 <code>WARN3("Values are: %d and '%s'", 5, "oops");</code>
196 Only one default category can be created per file, though multiple
197 non-defaults can be created and used.
199 \section log_API_easy 2.4 Putting all together: the easy interface
201 First of all, each module should register its own category into the categories
202 tree using \ref XBT_LOG_NEW_DEFAULT_SUBCATEGORY.
204 Then, logging should be done with the DEBUG<n>, VERB<n>, INFO<n>, WARN<n>,
205 ERROR<n> or CRITICAL<n> macro families. For each group, there is 6 different
206 macros (like DEBUG0, DEBUG1, DEBUG2, DEBUG3, DEBUG4 and DEBUG5), only differing
207 in the number of arguments passed along the format. This is because we want
208 SimGrid itself to keep compilable on ancient compiler not supporting variable
209 number of arguments to macros. But we should provide a macro simpler to use for
210 the users not interested in SP3 machines (FIXME).
212 Under GCC, these macro check there arguments the same way than printf does. So,
213 if you compile with -Wall, the folliwing code will issue a warning:
214 <code>DEBUG2("Found %s (id %f)", some_string, a_double)</code>
216 \section log_API_example 2.5 Example of use
218 Here is a more complete example:
223 / * create a category and a default subcategory * /
224 XBT_LOG_NEW_CATEGORY(VSS);
225 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(SA, VSS);
228 / * Now set the parent's priority. (the string would typcially be a runtime option) * /
229 xbt_log_control_set("SA.thresh=3");
231 / * This request is enabled, because WARNING >= INFO. * /
232 CWARN2(VSS, "Low fuel level.");
234 / * This request is disabled, because DEBUG < INFO. * /
235 CDEBUG2(VSS, "Starting search for nearest gas station.");
237 / * The default category SA inherits its priority from VSS. Thus,
238 the following request is enabled because INFO >= INFO. * /
239 INFO1("Located nearest gas station.");
241 / * This request is disabled, because DEBUG < INFO. * /
242 DEBUG1("Exiting gas station search");
247 \section log_user 3. User interface
249 \section log_use_conf 3.1 Configuration
250 Configuration is typically done during program initialization by invoking
251 the xbt_log_control_set() method. The control string passed to it typically
252 comes from the command line. Look at the documentation for that function for
253 the format of the control string.
255 Any SimGrid program can furthermore be configured at run time by passing a
256 --xbt-log argument on the command line (--gras-log, --msg-log and --surf-log
257 are synonyms provided by aestheticism). You can provide several of those
258 arguments to change the setting of several categories, they will be applied
259 from left to right. So,
260 \verbatim --xbt-log="root.thres=debug root.thres=critical"\endverbatim
261 should disable any logging.
263 Note that the quotes on above line are mandatory because there is a space in
264 the argument, so we are protecting ourselves from the shell, not from SimGrid.
265 We could also reach the same effect with this:
266 \verbatim --xbt-log=root.thres=debug --xbt-log=root.thres=critical\endverbatim
268 \section log_use_misc 3.2 Misc and Caveats
270 - Do not use any of the macros that start with '_'.
271 - Log4J has a 'rolling file appender' which you can select with a run-time
272 option and specify the max file size. This would be a nice default for
273 non-kernel applications.
274 - Careful, category names are global variables.
276 \section log_internals 4. Internal considerations
278 This module is a mess of macro black magic, and when it goes wrong, SimGrid
279 studently loose its ability to explain its problems. When messing around this
280 module, I often find useful to define XBT_LOG_MAYDAY (which turns it back to
281 good old printf) for the time of finding what's going wrong.
283 \section log_in_perf 4.1 Performance
285 Except for the first invocation of a given category, a disabled logging request
286 requires an a single comparison of a static variable to a constant.
288 There is also compile time constant, \ref XBT_LOG_STATIC_THRESHOLD, which
289 causes all logging requests with a lower priority to be optimized to 0 cost
290 by the compiler. By setting it to gras_log_priority_infinite, all logging
291 requests are statically disabled and cost nothing. Released executables
292 might be compiled with
293 \verbatim-DXBT_LOG_STATIC_THRESHOLD=gras_log_priority_infinite\endverbatim
295 Compiling with the \verbatim-DNLOG\endverbatim option disables all logging
296 requests at compilation time while the \verbatim-DNDEBUG\endverbatim disables
297 the requests of priority below INFO.
299 \todo Logging performance *may* be improved further by improving the message
300 propagation from appender to appender in the category tree.
302 \section log_in_app 4.2 Appenders
304 Each category has an optional appender. An appender is a pointer to a
305 structure which starts with a pointer to a doAppend() function. DoAppend()
306 prints a message to a log.
308 When a category is passed a message by one of the logging macros, the
309 category performs the following actions:
311 - if the category has an appender, the message is passed to the
312 appender's doAppend() function,
313 - if 'willLogToParent' is true for the category, the message is passed
314 to the category's parent.
316 By default, only the root category have an appender, and 'willLogToParent'
317 is true for any other category. This situation causes all messages to be
318 logged by the root category's appender.
320 The default appender function currently prints to stderr, and no other one
321 exist, even if more would be needed, like the one able to send the logs to a
322 remote dedicated server, or other ones offering different output formats.
323 This is on our TODO list for quite a while now, but your help would be
332 e_xbt_log_priority_t thresh;
333 } s_xbt_log_setting_t,*xbt_log_setting_t;
335 static xbt_dynar_t xbt_log_settings=NULL;
336 static void _free_setting(void *s) {
337 xbt_log_setting_t set=(xbt_log_setting_t)s;
340 /* free(set); FIXME: uncommenting this leads to segfault when more than one chunk is passed as gras-log */
344 const char *xbt_log_priority_names[8] = {
355 s_xbt_log_category_t _XBT_LOGV(XBT_LOG_ROOT_CAT) = {
357 "root", xbt_log_priority_uninitialized, 0,
361 XBT_LOG_NEW_CATEGORY(xbt,"All XBT categories (simgrid toolbox)");
362 XBT_LOG_NEW_CATEGORY(surf,"All SURF categories");
363 XBT_LOG_NEW_CATEGORY(msg,"All MSG categories");
364 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(log,xbt,"Loggings from the logging mechanism itself");
366 void xbt_log_init(int *argc,char **argv) {
370 /* Set logs and init log submodule */
371 for (i=1; i<*argc; i++) {
372 if (!strncmp(argv[i],"--gras-log=",strlen("--gras-log=")) ||
373 !strncmp(argv[i],"--surf-log=",strlen("--surf-log=")) ||
374 !strncmp(argv[i],"--msg-log=",strlen("--msg-log=")) ||
375 !strncmp(argv[i],"--xbt-log=",strlen("--xbt-log="))) {
376 opt=strchr(argv[i],'=');
378 xbt_log_control_set(opt);
379 DEBUG1("Did apply '%s' as log setting",opt);
380 /*remove this from argv*/
381 for (j=i+1; j<*argc; j++) {
386 i--; /* compensate effect of next loop incrementation */
391 void xbt_log_exit(void) {
392 VERB0("Exiting log");
393 xbt_dynar_free(&xbt_log_settings);
397 static void _apply_control(xbt_log_category_t cat) {
399 xbt_log_setting_t setting=NULL;
402 if (!xbt_log_settings)
405 xbt_assert0(cat,"NULL category");
406 xbt_assert(cat->name);
408 xbt_dynar_foreach(xbt_log_settings,cursor,setting) {
409 xbt_assert0(setting,"Damnit, NULL cat in the list");
410 xbt_assert1(setting->catname,"NULL setting(=%p)->catname",(void*)setting);
412 if (!strcmp(setting->catname,cat->name)) {
415 xbt_log_threshold_set(cat, setting->thresh);
416 xbt_dynar_cursor_rm(xbt_log_settings,&cursor);
418 if (cat->threshold <= xbt_log_priority_debug) {
419 s_xbt_log_event_t _log_ev =
420 {cat,xbt_log_priority_debug,__FILE__,_XBT_FUNCTION,__LINE__};
421 _xbt_log_event_log(&_log_ev,
422 "Apply settings for category '%s': set threshold to %s (=%d)",
424 xbt_log_priority_names[cat->threshold], cat->threshold);
428 if (!found && cat->threshold <= xbt_log_priority_verbose) {
429 s_xbt_log_event_t _log_ev =
430 {cat,xbt_log_priority_verbose,__FILE__,_XBT_FUNCTION,__LINE__};
431 _xbt_log_event_log(&_log_ev,
432 "Category '%s': inherited threshold = %s (=%d)",
434 xbt_log_priority_names[cat->threshold], cat->threshold);
439 void _xbt_log_event_log( xbt_log_event_t ev, const char *fmt, ...) {
440 xbt_log_category_t cat = ev->cat;
441 va_start(ev->ap, fmt);
443 xbt_log_appender_t appender = cat->appender;
444 if (appender != NULL) {
445 appender->do_append(appender, ev, fmt);
447 if (!cat->willLogToParent)
455 static void _cat_init(xbt_log_category_t category) {
456 if (category == &_XBT_LOGV(XBT_LOG_ROOT_CAT)) {
457 category->threshold = xbt_log_priority_info;
458 category->appender = xbt_log_default_appender;
460 xbt_log_parent_set(category, category->parent);
462 _apply_control(category);
466 * This gets called the first time a category is referenced and performs the
468 * Also resets threshold to inherited!
470 int _xbt_log_cat_init(e_xbt_log_priority_t priority,
471 xbt_log_category_t category) {
475 return priority >= category->threshold;
478 void xbt_log_parent_set(xbt_log_category_t cat,
479 xbt_log_category_t parent) {
481 xbt_assert0(cat,"NULL category to be given a parent");
482 xbt_assert1(parent,"The parent category of %s is NULL",cat->name);
484 /* unlink from current parent */
485 if (cat->threshold != xbt_log_priority_uninitialized) {
486 xbt_log_category_t* cpp = &parent->firstChild;
487 while(*cpp != cat && *cpp != NULL) {
488 cpp = &(*cpp)->nextSibling;
490 xbt_assert(*cpp == cat);
491 *cpp = cat->nextSibling;
495 cat->parent = parent;
496 cat->nextSibling = parent->firstChild;
497 parent->firstChild = cat;
499 /* Make sure parent is initialized */
500 if (parent->threshold == xbt_log_priority_uninitialized) {
505 cat->threshold = parent->threshold;
506 cat->isThreshInherited = 1;
507 } /* log_setParent */
509 static void _set_inherited_thresholds(xbt_log_category_t cat) {
510 xbt_log_category_t child = cat->firstChild;
511 for( ; child != NULL; child = child->nextSibling) {
512 if (child->isThreshInherited) {
513 if (cat != &_XBT_LOGV(log))
514 VERB3("Set category threshold of %s to %s (=%d)",
515 child->name,xbt_log_priority_names[cat->threshold],cat->threshold);
516 child->threshold = cat->threshold;
517 _set_inherited_thresholds(child);
522 void xbt_log_threshold_set(xbt_log_category_t cat,
523 e_xbt_log_priority_t threshold) {
524 cat->threshold = threshold;
525 cat->isThreshInherited = 0;
526 _set_inherited_thresholds(cat);
529 static void _xbt_log_parse_setting(const char* control_string,
530 xbt_log_setting_t set) {
531 const char *name, *dot, *eq;
534 if (!*control_string)
536 DEBUG1("Parse log setting '%s'",control_string);
538 control_string += strspn(control_string, " ");
539 name = control_string;
540 control_string += strcspn(control_string, ".= ");
541 dot = control_string;
542 control_string += strcspn(control_string, "= ");
544 control_string += strcspn(control_string, " ");
546 xbt_assert1(*dot == '.' && *eq == '=',
547 "Invalid control string '%s'",control_string);
549 if (!strncmp(dot + 1, "thresh", min(eq - dot - 1,strlen("thresh")))) {
551 char *neweq=xbt_strdup(eq+1);
554 while (*(++p) != '\0') {
555 if (*p >= 'a' && *p <= 'z') {
560 DEBUG1("New priority name = %s",neweq);
561 for (i=0; i<xbt_log_priority_infinite-1; i++) {
562 if (!strncmp(xbt_log_priority_names[i],neweq,p-eq)) {
563 DEBUG1("This is priority %d",i);
567 if (i<xbt_log_priority_infinite-1) {
570 xbt_assert1(FALSE,"Unknown priority name: %s",eq+1);
575 snprintf(buff,min(512,eq - dot - 1),"%s",dot+1);
576 xbt_assert1(FALSE,"Unknown setting of the log category: %s",buff);
578 set->catname=(char*)xbt_malloc(dot - name+1);
580 strncpy(set->catname,name,dot-name);
581 set->catname[dot-name]='\0'; /* Just in case */
582 DEBUG1("This is for cat '%s'", set->catname);
585 static xbt_log_category_t _xbt_log_cat_searchsub(xbt_log_category_t cat,char *name) {
586 xbt_log_category_t child;
588 if (!strcmp(cat->name,name)) {
591 for(child=cat->firstChild ; child != NULL; child = child->nextSibling) {
592 return _xbt_log_cat_searchsub(child,name);
594 THROW0(not_found_error,0,"No such category");
597 static void _cleanup_double_spaces(char *s) {
620 if (e ^ !isspace(*p))
631 * \param control_string What to parse
633 * Typically passed a command-line argument. The string has the syntax:
635 * ( [category] "." [keyword] "=" value (" ")... )...
637 * where [category] is one the category names (see \ref XBT_log_cats for a complete list)
638 * and keyword is one of the following:
640 * - thres: category's threshold priority. Possible values:
641 * TRACE,DEBUG,VERBOSE,INFO,WARNING,ERROR,CRITICAL
645 * This routine may only be called once and that must be before any other
646 * logging command! Typically, this is done from main().
647 * \todo the previous warning seems a bit old and need double checking
649 void xbt_log_control_set(const char* control_string) {
650 xbt_log_setting_t set;
655 DEBUG1("Parse log settings '%s'",control_string);
656 if (control_string == NULL)
658 if (xbt_log_settings == NULL)
659 xbt_log_settings = xbt_dynar_new(sizeof(xbt_log_setting_t),
662 set = xbt_new(s_xbt_log_setting_t,1);
663 cs=xbt_strdup(control_string);
665 _cleanup_double_spaces(cs);
668 xbt_log_category_t cat;
680 _xbt_log_parse_setting(p,set);
683 cat = _xbt_log_cat_searchsub(&_XBT_LOGV(root),set->catname);
686 if (e.category != not_found_error)
691 DEBUG0("Store for further application");
692 DEBUG1("push %p to the settings",(void*)set);
693 xbt_dynar_push(xbt_log_settings,&set);
694 /* malloc in advance the next slot */
695 set = xbt_new(s_xbt_log_setting_t,1);
699 DEBUG0("Apply directly");
701 xbt_log_threshold_set(cat,set->thresh);
708 void xbt_log_appender_set(xbt_log_category_t cat, xbt_log_appender_t app) {