Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
23c908ba4ab69673423872c394539d91f393b2ce
[simgrid.git] / src / xbt / log.c
1 /* log - a generic logging facility in the spirit of log4j                  */
2
3 /* Copyright (c) 2004-2011. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9
10 #include <stdarg.h>
11 #include <ctype.h>
12 #include <stdio.h>              /* snprintf */
13 #include <stdlib.h>             /* snprintf */
14
15 #include "portable.h"           /* to get a working stdarg.h */
16
17 #include "xbt_modinter.h"
18
19 #include "xbt/misc.h"
20 #include "xbt/ex.h"
21 #include "xbt/str.h"
22 #include "xbt/sysdep.h"
23 #include "xbt/log_private.h"
24 #include "xbt/dynar.h"
25 #include "xbt/xbt_os_thread.h"
26
27 XBT_PUBLIC_DATA(int) (*xbt_pid) ();
28 int xbt_log_no_loc = 0;         /* if set to true (with --log=no_loc), file localization will be omitted (for tesh tests) */
29 static xbt_os_rmutex_t log_cat_init_mutex = NULL;
30
31 /** \addtogroup XBT_log
32  *
33  *  This section describes the API to the log functions used
34  *  everywhere in this project.
35
36 \section XBT_log_toc Table of contents
37
38  - \ref log_overview
39    - \ref log_cat
40    - \ref log_pri
41    - \ref log_app
42    - \ref log_hist
43  - \ref log_API
44    - \ref log_API_cat
45    - \ref log_API_pri
46    - \ref log_API_isenabled
47    - \ref log_API_subcat
48    - \ref log_API_easy
49    - \ref log_API_example
50  - \ref log_user
51    - \ref log_use_conf
52      - \ref log_use_conf_thres
53      - \ref log_use_conf_multi
54      - \ref log_use_conf_fmt
55      - \ref log_use_conf_app
56      - \ref log_use_conf_add
57    - \ref log_use_misc
58  - \ref log_internals
59    - \ref log_in_perf
60    - \ref log_in_app
61  - \ref XBT_log_cats
62
63 \section log_overview 1. Introduction
64
65 This module is in charge of handling the log messages of every SimGrid
66 program. The main design goal are:
67
68   - <b>configurability</b>: the user can choose <i>at runtime</i> what messages to show and
69     what to hide, as well as how messages get displayed.
70   - <b>ease of use</b>: both to the programmer (using preprocessor macros black magic)
71     and to the user (with command line options)
72   - <b>performances</b>: logging shouldn't slow down the program when turned off, for example
73   - deal with <b>distributed settings</b>: SimGrid programs are [often] distributed ones,
74     and the logging mechanism allows to syndicate each and every log source into the same place.
75     At least, its design would allow to, once we write the last missing pieces
76
77 There is three main concepts in SimGrid's logging mechanism: <i>category</i>,
78 <i>priority</i> and <i>appender</i>. These three concepts work together to
79 enable developers to log messages according to message type and priority, and
80 to control at runtime how these messages are formatted and where they are
81 reported.
82
83 \subsection log_cat 1.1 Category hierarchy
84
85 The first and foremost advantage of any logging API over plain printf()
86 resides in its ability to disable certain log statements while allowing
87 others to print unhindered. This capability assumes that the logging space,
88 that is, the space of all possible logging statements, is categorized
89 according to some developer-chosen criteria.
90
91 This observation led to choosing category as the central concept of the
92 system. In a certain sense, they can be considered as logging topics or
93 channels.
94
95 \subsection log_pri 1.2 Logging priorities
96
97 The user can naturally declare interest into this or that logging category, but
98 he also can specify the desired level of details for each of them. This is
99 controlled by the <i>priority</i> concept (which should maybe be renamed to
100 <i>severity</i>).
101
102 Empirically, the user can specify that he wants to see every debugging message
103 of GRAS while only being interested into the messages at level "error" or
104 higher about the XBT internals.
105
106 \subsection log_app 1.3 Message appenders
107
108 The message appenders are the elements in charge of actually displaying the
109 message to the user. For now, only two appenders exist: the default one prints
110 stuff on stderr while it is possible to create appenders printing to a specific
111 file.
112
113 Other are planed (such as the one sending everything to a remote server,
114 or the one using only a fixed amount of lines in a file, and rotating content on
115 need). One day, for sure ;)
116
117 \subsection log_lay 1.4 Message layouts
118
119 The message layouts are the elements in charge of choosing how each message
120 will look like. Their result is a string which is then passed to the appender
121 attached to the category to be displayed.
122
123 For now, there is two layouts: The simple one, which is good for most cases,
124 and another one allowing users to specify the format they want.
125 \ref log_use_conf provides more info on this.
126
127 \subsection log_hist 1.5 History of this module
128
129 Historically, this module is an adaptation of the log4c project, which is dead
130 upstream, and which I was given the permission to fork under the LGPL licence
131 by the log4c's authors. The log4c project itself was loosely based on the
132 Apache project's Log4J, which also inspired Log4CC, Log4py and so on. Our work
133 differs somehow from these projects anyway, because the C programming language
134 is not object oriented.
135
136 \section log_API 2. Programmer interface
137
138 \subsection log_API_cat 2.1 Constructing the category hierarchy
139
140 Every category is declared by providing a name and an optional
141 parent. If no parent is explicitly named, the root category, LOG_ROOT_CAT is
142 the category's parent.
143
144 A category is created by a macro call at the top level of a file.  A
145 category can be created with any one of the following macros:
146
147  - \ref XBT_LOG_NEW_CATEGORY(MyCat,desc); Create a new root
148  - \ref XBT_LOG_NEW_SUBCATEGORY(MyCat, ParentCat,desc);
149     Create a new category being child of the category ParentCat
150  - \ref XBT_LOG_NEW_DEFAULT_CATEGORY(MyCat,desc);
151     Like XBT_LOG_NEW_CATEGORY, but the new category is the default one
152       in this file
153  -  \ref XBT_LOG_NEW_DEFAULT_SUBCATEGORY(MyCat, ParentCat,desc);
154     Like XBT_LOG_NEW_SUBCATEGORY, but the new category is the default one
155       in this file
156
157 The parent cat can be defined in the same file or in another file (in
158 which case you want to use the \ref XBT_LOG_EXTERNAL_CATEGORY macro to make
159 it visible in the current file), but each category may have only one
160 definition. Likewise, you can use a category defined in another file as 
161 default one using \ref XBT_LOG_EXTERNAL_DEFAULT_CATEGORY
162
163 Typically, there will be a Category for each module and sub-module, so you
164 can independently control logging for each module.
165
166 For a list of all existing categories, please refer to the \ref XBT_log_cats
167 section. This file is generated automatically from the SimGrid source code, so
168 it should be complete and accurate.
169
170 \section log_API_pri 2.2 Declaring message priority
171
172 A category may be assigned a threshold priority. The set of priorities are
173 defined by the \ref e_xbt_log_priority_t enum. All logging request under
174 this priority will be discarded.
175
176 If a given category is not assigned a threshold priority, then it inherits
177 one from its closest ancestor with an assigned threshold. To ensure that all
178 categories can eventually inherit a threshold, the root category always has
179 an assigned threshold priority.
180
181 Logging requests are made by invoking a logging macro on a category.  All of
182 the macros have a printf-style format string followed by arguments. If you
183 compile with the -Wall option, gcc will warn you for unmatched arguments, ie
184 when you pass a pointer to a string where an integer was specified by the
185 format. This is usually a good idea.
186
187 Here is an example of the most basic type of macro. This is a logging
188 request with priority <i>warning</i>.
189
190 <code>XBT_CLOG(MyCat, gras_log_priority_warning, "Values are: %d and '%s'", 5,
191 "oops");</code>
192
193 A logging request is said to be enabled if its priority is higher than or
194 equal to the threshold priority of its category. Otherwise, the request is
195 said to be disabled. A category without an assigned priority will inherit
196 one from the hierarchy.
197
198 It is possible to use any non-negative integer as a priority. If, as in the
199 example, one of the standard priorities is used, then there is a convenience
200 macro that is typically used instead. For example, the above example is
201 equivalent to the shorter:
202
203 <code>XBT_CWARN(MyCat, "Values are: %d and '%s'", 5, "oops");</code>
204
205 \section log_API_isenabled 2.3 Checking if a particular category/priority is enabled
206
207 It is sometimes useful to check whether a particular category is
208 enabled at a particular priority. One example is when you want to do
209 some extra computation to prepare a nice debugging message. There is
210 no use of doing so if the message won't be used afterward because
211 debugging is turned off.
212
213 Doing so is extremely easy, thanks to the XBT_LOG_ISENABLED(category, priority).
214
215 \section log_API_subcat 2.4 Using a default category (the easy interface)
216
217 If \ref XBT_LOG_NEW_DEFAULT_SUBCATEGORY(MyCat, Parent) or
218 \ref XBT_LOG_NEW_DEFAULT_CATEGORY(MyCat) is used to create the
219 category, then the even shorter form can be used:
220
221 <code>XBT_WARN("Values are: %s and '%d'", 5, "oops");</code>
222
223 Only one default category can be created per file, though multiple
224 non-defaults can be created and used.
225
226 \section log_API_easy 2.5 Putting all together: the easy interface
227
228 First of all, each module should register its own category into the categories
229 tree using \ref XBT_LOG_NEW_DEFAULT_SUBCATEGORY.
230
231 Then, logging should be done with the #XBT_DEBUG, #XBT_VERB, #XBT_INFO,
232 #XBT_WARN, #XBT_ERROR and #XBT_CRITICAL macros.
233
234 Under GCC, these macro check there arguments the same way than printf does. So,
235 if you compile with -Wall, the following code will issue a warning:
236 <code>XBT_DEBUG("Found %s (id %d)", some_string, a_double)</code>
237
238 If you want to specify the category to log onto (for example because you
239 have more than one category per file, add a C before the name of the log
240 producing macro (ie, use #XBT_CDEBUG, #XBT_CVERB, #XBT_CINFO, #XBT_CWARN,
241 #XBT_CERROR and #XBT_CCRITICAL and friends), and pass the category name as
242 first argument.
243
244 The TRACE priority is not used the same way than the other. You should use
245 the #XBT_IN, #XBT_OUT and #XBT_HERE macros instead.
246
247 \section log_API_example 2.6 Example of use
248
249 Here is a more complete example:
250
251 \verbatim
252 #include "xbt/log.h"
253
254 / * create a category and a default subcategory * /
255 XBT_LOG_NEW_CATEGORY(VSS);
256 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(SA, VSS);
257
258 int main() {
259        / * Now set the parent's priority.  (the string would typcially be a runtime option) * /
260        xbt_log_control_set("SA.thresh:3");
261
262        / * This request is enabled, because WARNING >= INFO. * /
263        XBT_CWARN(VSS, "Low fuel level.");
264
265        / * This request is disabled, because DEBUG < INFO. * /
266        XBT_CDEBUG(VSS, "Starting search for nearest gas station.");
267
268        / * The default category SA inherits its priority from VSS. Thus,
269           the following request is enabled because INFO >= INFO.  * /
270        XBT_INFO("Located nearest gas station.");
271
272        / * This request is disabled, because DEBUG < INFO. * /
273        XBT_DEBUG("Exiting gas station search");
274 }
275 \endverbatim
276
277 Another example can be found in the relevant part of the GRAS tutorial:
278 \ref GRAS_tut_tour_logs.
279
280 \section log_user 3. User interface
281
282 \section log_use_conf 3.1 Configuration
283
284 Although rarely done, it is possible to configure the logs during
285 program initialization by invoking the xbt_log_control_set() method
286 manually. A more conventional way is to use the --log command line
287 argument. xbt_init() (called by MSG_init(), gras_init() and friends)
288 checks and deals properly with such arguments.
289
290 The following command line arguments exist, but are deprecated and
291 may disappear in the future: --xbt-log, --gras-log, --msg-log and
292 --surf-log.
293
294 \subsection log_use_conf_thres 3.1.1 Threshold configuration
295
296 The most common setting is to control which logging event will get
297 displayed by setting a threshold to each category through the
298 <tt>thres</tt> keyword.
299
300 For example, \verbatim --log=root.thres:debug\endverbatim will make
301 SimGrid <b>extremely</b> verbose while \verbatim
302 --log=root.thres:critical\endverbatim should shut it almost
303 completely off. The full list of recognized thresholds is the following:
304
305  - trace: enter and return of some functions
306  - debug: crufty output
307  - verbose: verbose output for the user wanting more
308  - info: output about the regular functionning
309  - warning: minor issue encountered
310  - error: issue encountered
311  - critical: major issue encountered 
312
313 \subsection log_use_conf_multi 3.1.2 Passing several settings
314
315 You can provide several of those arguments to change the setting of several
316 categories, they will be applied from left to right. So,
317 \verbatim --log="root.thres:debug root.thres:critical"\endverbatim should
318 disable almost any logging.
319
320 Note that the quotes on above line are mandatory because there is a space in
321 the argument, so we are protecting ourselves from the shell, not from SimGrid.
322 We could also reach the same effect with this:
323 \verbatim --log=root.thres:debug --log=root.thres:critical\endverbatim
324
325 \subsection log_use_conf_fmt 3.1.3 Format configuration
326
327 As with SimGrid 3.3, it is possible to control the format of log
328 messages. This is done through the <tt>fmt</tt> keyword. For example,
329 \verbatim --log=root.fmt:%m\endverbatim reduces the output to the
330 user-message only, removing any decoration such as the date, or the
331 process ID, everything.
332
333 Here are the existing format directives:
334
335  - %%: the % char
336  - %%n: platform-dependent line separator (LOG4J compatible)
337  - %%e: plain old space (SimGrid extension)
338
339  - %%m: user-provided message
340
341  - %%c: Category name (LOG4J compatible)
342  - %%p: Priority name (LOG4J compatible)
343
344  - %%h: Hostname (SimGrid extension)
345  - %%P: Process name (SimGrid extension)
346  - %%t: Thread "name" (LOG4J compatible -- actually the address of the thread in memory)
347  - %%i: Process PID (SimGrid extension -- this is a 'i' as in 'i'dea)
348
349  - %%F: file name where the log event was raised (LOG4J compatible)
350  - %%l: location where the log event was raised (LOG4J compatible, like '%%F:%%L' -- this is a l as in 'l'etter)
351  - %%L: line number where the log event was raised (LOG4J compatible)
352  - %%M: function name (LOG4J compatible -- called method name here of course).
353    Defined only when using gcc because there is no __FUNCTION__ elsewhere.
354
355  - %%b: full backtrace (Called %%throwable in LOG4J).
356    Defined only under windows or when using the GNU libc because backtrace() is not defined
357    elsewhere, and we only have a fallback for windows boxes, not mac ones for example.
358  - %%B: short backtrace (only the first line of the %%b).
359    Called %%throwable{short} in LOG4J; defined where %%b is.
360
361  - %%d: date (UNIX-like epoch)
362  - %%r: application age (time elapsed since the beginning of the application)
363
364
365 If you want to mimic the simple layout with the format one, you would use this
366 format: '[%%h:%%i:(%%i) %%r] %%l: [%%c/%%p] %%m%%n'. This is not completely correct
367 because the simple layout do not display the message location for messages at
368 priority INFO (thus, the fmt is '[%%h:%%i:(%%i) %%r] [%%c/%%p] %%m%%n' in this
369 case). Moreover, if there is no process name (ie, messages coming from the
370 library itself, or test programs doing strange things) do not display the
371 process identity (thus, fmt is '[%%r] %%l: [%%c/%%p] %%m%%n' in that case, and '[%%r]
372 [%%c/%%p] %%m%%n' if they are at priority INFO).
373
374 For now, there is only two format modifiers: the precision and the
375 width fields. You can for example specify %.4r to get the application
376 age with 4 numbers after the radix, or %15p to get the process name
377 on 15 columns. Finally, you can specify %10.6r to get the time on at
378 most 10 columns, with 6 numbers after the radix. 
379
380 Note that when specifying the width, it is filled with spaces. That
381 is to say that for example %5r in your format is converted to "% 5f"
382 for printf (note the extra space); there is no way to fill the empty
383 columns with 0 (ie, pass "%05f" to printf). Another limitation is
384 that you cannot set specific layouts to the several priorities.
385
386 \subsection log_use_conf_app 3.1.4 Category appender
387
388 As with SimGrid 3.3, it is possible to control the appender of log
389 messages. This is done through the <tt>app</tt> keyword. For example,
390 \verbatim --log=root.app:file:mylogfile\endverbatim redirects the output
391 to the file mylogfile.
392
393 Any appender setup this way have its own layout format (simple one by default),
394 so you may have to change it too afterward. Moreover, the additivity of the log category
395 is also set to false to prevent log event displayed by this appender to "leak" to any other
396 appender higher in the hierarchy. If it is not what you wanted, you can naturally change it
397 manually.
398
399 \subsection log_use_conf_add 3.1.5 Category additivity
400
401 The <tt>add</tt> keyword allows to specify the additivity of a
402 category (see \ref log_in_app). '0', '1', 'no', 'yes', 'on'
403 and 'off' are all valid values, with 'yes' as default.
404
405 The following example resets the additivity of the xbt category to true (which is its default value).
406 \verbatim --log=xbt.add:yes\endverbatim
407
408 \section log_use_misc 3.2 Misc and Caveats
409
410   - Do not use any of the macros that start with '_'.
411   - Log4J has a 'rolling file appender' which you can select with a run-time
412     option and specify the max file size. This would be a nice default for
413     non-kernel applications.
414   - Careful, category names are global variables.
415
416 \section log_internals 4. Internal considerations
417
418 This module is a mess of macro black magic, and when it goes wrong,
419 SimGrid studently loose its ability to explain its problems. When
420 messing around this module, I often find useful to define
421 XBT_LOG_MAYDAY (which turns it back to good old printf) for the time
422 of finding what's going wrong. But things are quite verbose when
423 everything is enabled...
424
425 \section log_in_perf 4.1 Performance
426
427 Except for the first invocation of a given category, a disabled logging request
428 requires an a single comparison of a static variable to a constant.
429
430 There is also compile time constant, \ref XBT_LOG_STATIC_THRESHOLD, which
431 causes all logging requests with a lower priority to be optimized to 0 cost
432 by the compiler. By setting it to gras_log_priority_infinite, all logging
433 requests are statically disabled at compile time and cost nothing. Released executables
434 <i>might</i>  be compiled with (note that it will prevent users to debug their problems)
435 \verbatim-DXBT_LOG_STATIC_THRESHOLD=gras_log_priority_infinite\endverbatim
436
437 Compiling with the \verbatim-DNLOG\endverbatim option disables all logging
438 requests at compilation time while the \verbatim-DNDEBUG\endverbatim disables
439 the requests of priority below INFO.
440
441 \todo Logging performance *may* be improved further by improving the message
442 propagation from appender to appender in the category tree.
443
444 \section log_in_app 4.2 Appenders
445
446 Each category has an optional appender. An appender is a pointer to a
447 structure which starts with a pointer to a do_append() function. do_append()
448 prints a message to a log.
449
450 When a category is passed a message by one of the logging macros, the
451 category performs the following actions:
452
453   - if the category has an appender, the message is passed to the
454     appender's do_append() function,
455   - if additivity is true for the category, the message is passed to
456     the category's parent. Additivity is true by default, and can be
457     controlled by xbt_log_additivity_set() or something like --log=root.add:1 (see \ref log_use_conf_add).
458     Also, when you add an appender to a category, its additivity is automatically turned to off.
459     Turn it back on afterward if it is not what you wanted.
460
461 By default, only the root category have an appender, and any other category has
462 its additivity set to true. This causes all messages to be logged by the root
463 category's appender.
464
465 The default appender function currently prints to stderr, and the only other
466 existing one writes to the specified file. More would be needed, like the one
467 able to send the logs to a remote dedicated server.
468 This is on our TODO list for quite a while now, but your help would be
469 welcome here, too. */
470
471 xbt_log_appender_t xbt_log_default_appender = NULL;     /* set in log_init */
472 xbt_log_layout_t xbt_log_default_layout = NULL; /* set in log_init */
473
474 typedef struct {
475   char *catname;
476   char *fmt;
477   e_xbt_log_priority_t thresh;
478   int additivity;
479   xbt_log_appender_t appender;
480 } s_xbt_log_setting_t, *xbt_log_setting_t;
481
482 static xbt_dynar_t xbt_log_settings = NULL;
483
484 static void _free_setting(void *s)
485 {
486   xbt_log_setting_t set = *(xbt_log_setting_t *) s;
487   if (set) {
488     free(set->catname);
489     free(set->fmt);
490     free(set);
491   }
492 }
493
494 static void _xbt_log_cat_apply_set(xbt_log_category_t category,
495                                    xbt_log_setting_t setting);
496
497 const char *xbt_log_priority_names[8] = {
498   "NONE",
499   "TRACE",
500   "DEBUG",
501   "VERBOSE",
502   "INFO",
503   "WARNING",
504   "ERROR",
505   "CRITICAL"
506 };
507
508 s_xbt_log_category_t _XBT_LOGV(XBT_LOG_ROOT_CAT) = {
509   NULL /*parent */ , NULL /* firstChild */ , NULL /* nextSibling */ ,
510       "root",
511       0 /*initialized */, xbt_log_priority_uninitialized /* threshold */ ,
512       0 /* isThreshInherited */ ,
513       NULL /* appender */ , NULL /* layout */ ,
514       0                         /* additivity */
515 };
516
517 XBT_LOG_NEW_CATEGORY(xbt, "All XBT categories (simgrid toolbox)");
518 XBT_LOG_NEW_CATEGORY(surf, "All SURF categories");
519 XBT_LOG_NEW_CATEGORY(msg, "All MSG categories");
520 XBT_LOG_NEW_CATEGORY(simix, "All SIMIX categories");
521 XBT_LOG_NEW_CATEGORY(mc, "All MC categories");
522 XBT_LOG_NEW_CATEGORY(bindings, "All bindings categories");
523
524 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(log, xbt,
525                                 "Loggings from the logging mechanism itself");
526
527 /* create the default appender and install it in the root category,
528    which were already created (damnit. Too slow little beetle) */
529 void xbt_log_preinit(void)
530 {
531   xbt_log_default_appender = xbt_log_appender_file_new(NULL);
532   xbt_log_default_layout = xbt_log_layout_simple_new(NULL);
533   _XBT_LOGV(XBT_LOG_ROOT_CAT).appender = xbt_log_default_appender;
534   _XBT_LOGV(XBT_LOG_ROOT_CAT).layout = xbt_log_default_layout;
535   log_cat_init_mutex = xbt_os_rmutex_init();
536 }
537
538 /** @brief Get all logging settings from the command line
539  *
540  * xbt_log_control_set() is called on each string we got from cmd line
541  */
542 void xbt_log_init(int *argc, char **argv)
543 {
544   int i, j;
545   char *opt;
546
547   //    _XBT_LOGV(log).threshold = xbt_log_priority_debug; /* uncomment to set the LOG category to debug directly */
548
549   /* Set logs and init log submodule */
550   for (i = 1; i < *argc; i++) {
551     if (!strncmp(argv[i], "--log=", strlen("--log=")) ||
552         !strncmp(argv[i], "--gras-log=", strlen("--gras-log=")) ||
553         !strncmp(argv[i], "--surf-log=", strlen("--surf-log=")) ||
554         !strncmp(argv[i], "--msg-log=", strlen("--msg-log=")) ||
555         !strncmp(argv[i], "--simix-log=", strlen("--simix-log=")) ||
556         !strncmp(argv[i], "--xbt-log=", strlen("--xbt-log="))) {
557
558       if (strncmp(argv[i], "--log=", strlen("--log=")))
559         XBT_WARN
560             ("Option %.*s is deprecated and will disapear in the future. Use --log instead.",
561              (int) (strchr(argv[i], '=') - argv[i]), argv[i]);
562
563       opt = strchr(argv[i], '=');
564       opt++;
565       xbt_log_control_set(opt);
566       XBT_DEBUG("Did apply '%s' as log setting", opt);
567       /*remove this from argv */
568
569       for (j = i + 1; j < *argc; j++) {
570         argv[j - 1] = argv[j];
571       }
572
573       argv[j - 1] = NULL;
574       (*argc)--;
575       i--;                      /* compensate effect of next loop incrementation */
576     }
577   }
578 }
579
580 static void log_cat_exit(xbt_log_category_t cat)
581 {
582   xbt_log_category_t child;
583
584   if (cat->appender) {
585     if (cat->appender->free_)
586       cat->appender->free_(cat->appender);
587     free(cat->appender);
588   }
589   if (cat->layout) {
590     if (cat->layout->free_)
591       cat->layout->free_(cat->layout);
592     free(cat->layout);
593   }
594
595   for (child = cat->firstChild; child != NULL; child = child->nextSibling)
596     log_cat_exit(child);
597 }
598
599 void xbt_log_postexit(void)
600 {
601   XBT_VERB("Exiting log");
602   xbt_os_rmutex_destroy(log_cat_init_mutex);
603   xbt_dynar_free(&xbt_log_settings);
604   log_cat_exit(&_XBT_LOGV(XBT_LOG_ROOT_CAT));
605 }
606
607  /* Size of the static string in which we  build the log string */
608 #define XBT_LOG_STATIC_BUFFER_SIZE 2048
609 /* Minimum size of the dynamic string in which we build the log string
610    (should be greater than XBT_LOG_STATIC_BUFFER_SIZE) */
611 #define XBT_LOG_DYNAMIC_BUFFER_SIZE 4096
612
613 void _xbt_log_event_log(xbt_log_event_t ev, const char *fmt, ...)
614 {
615   xbt_log_category_t cat = ev->cat;
616
617   xbt_assert(ev->priority >= 0,
618              "Negative logging priority naturally forbidden");
619   xbt_assert(ev->priority < sizeof(xbt_log_priority_names),
620              "Priority %d is greater than the biggest allowed value",
621              ev->priority);
622
623   do {
624     xbt_log_appender_t appender = cat->appender;
625
626     if (!appender)
627       continue;                 /* No appender, try next */
628
629     xbt_assert(cat->layout,
630                "No valid layout for the appender of category %s", cat->name);
631
632     /* First, try with a static buffer */
633     if (XBT_LOG_STATIC_BUFFER_SIZE) {
634       char buff[XBT_LOG_STATIC_BUFFER_SIZE];
635       int done;
636       ev->buffer = buff;
637       ev->buffer_size = sizeof buff;
638       va_start(ev->ap, fmt);
639       done = cat->layout->do_layout(cat->layout, ev, fmt);
640       va_end(ev->ap);
641       if (done) {
642         appender->do_append(appender, buff);
643         continue;               /* Ok, that worked: go next */
644       }
645     }
646
647     /* The static buffer was too small, use a dynamically expanded one */
648     ev->buffer_size = XBT_LOG_DYNAMIC_BUFFER_SIZE;
649     ev->buffer = xbt_malloc(ev->buffer_size);
650     while (1) {
651       int done;
652       va_start(ev->ap, fmt);
653       done = cat->layout->do_layout(cat->layout, ev, fmt);
654       va_end(ev->ap);
655       if (done)
656         break;                  /* Got it */
657       ev->buffer_size *= 2;
658       ev->buffer = xbt_realloc(ev->buffer, ev->buffer_size);
659     }
660     appender->do_append(appender, ev->buffer);
661     xbt_free(ev->buffer);
662
663   } while (cat->additivity && (cat = cat->parent, 1));
664 }
665
666 #undef XBT_LOG_DYNAMIC_BUFFER_SIZE
667 #undef XBT_LOG_STATIC_BUFFER_SIZE
668
669 /* NOTE:
670  *
671  * The standard logging macros use _XBT_LOG_ISENABLED, which calls
672  * _xbt_log_cat_init().  Thus, if we want to avoid an infinite
673  * recursion, we can not use the standard logging macros in
674  * _xbt_log_cat_init(), and in all functions called from it.
675  *
676  * To circumvent the problem, we define the macro_xbt_log_init() as
677  * (0) for the length of the affected functions, and we do not forget
678  * to undefine it at the end!
679  */
680
681 static void _xbt_log_cat_apply_set(xbt_log_category_t category,
682                                    xbt_log_setting_t setting)
683 {
684 #define _xbt_log_cat_init(a, b) (0)
685
686   if (setting->thresh != xbt_log_priority_uninitialized) {
687     xbt_log_threshold_set(category, setting->thresh);
688
689     XBT_DEBUG("Apply settings for category '%s': set threshold to %s (=%d)",
690            category->name, xbt_log_priority_names[category->threshold],
691            category->threshold);
692   }
693
694   if (setting->fmt) {
695     xbt_log_layout_set(category, xbt_log_layout_format_new(setting->fmt));
696
697     XBT_DEBUG("Apply settings for category '%s': set format to %s",
698            category->name, setting->fmt);
699   }
700
701   if (setting->additivity != -1) {
702     xbt_log_additivity_set(category, setting->additivity);
703
704     XBT_DEBUG("Apply settings for category '%s': set additivity to %s",
705            category->name, (setting->additivity ? "on" : "off"));
706   }
707   if (setting->appender) {
708     xbt_log_appender_set(category, setting->appender);
709     if (!category->layout)
710       xbt_log_layout_set(category, xbt_log_layout_simple_new(NULL));
711     category->additivity = 0;
712     XBT_DEBUG("Set %p as appender of category '%s'",
713            setting->appender, category->name);
714   }
715 #undef _xbt_log_cat_init
716 }
717
718 /*
719  * This gets called the first time a category is referenced and performs the
720  * initialization.
721  * Also resets threshold to inherited!
722  */
723 int _xbt_log_cat_init(xbt_log_category_t category,
724                       e_xbt_log_priority_t priority)
725 {
726 #define _xbt_log_cat_init(a, b) (0)
727
728   if (log_cat_init_mutex != NULL) {
729     xbt_os_rmutex_acquire(log_cat_init_mutex);
730   }
731
732   if (category->initialized) {
733     if (log_cat_init_mutex != NULL) {
734       xbt_os_rmutex_release(log_cat_init_mutex);
735     }
736     return priority >= category->threshold;
737   }
738
739   unsigned int cursor;
740   xbt_log_setting_t setting = NULL;
741   int found = 0;
742
743   XBT_DEBUG("Initializing category '%s' (firstChild=%s, nextSibling=%s)",
744          category->name,
745          (category->firstChild ? category->firstChild->name : "none"),
746          (category->nextSibling ? category->nextSibling->name : "none"));
747
748   if (category == &_XBT_LOGV(XBT_LOG_ROOT_CAT)) {
749     category->threshold = xbt_log_priority_info;
750     category->appender = xbt_log_default_appender;
751     category->layout = xbt_log_default_layout;
752   } else {
753
754     if (!category->parent)
755       category->parent = &_XBT_LOGV(XBT_LOG_ROOT_CAT);
756
757     XBT_DEBUG("Set %s (%s) as father of %s ",
758            category->parent->name,
759            (category->parent->initialized ?
760             xbt_log_priority_names[category->parent->threshold] : "uninited"),
761            category->name);
762     xbt_log_parent_set(category, category->parent);
763
764     if (XBT_LOG_ISENABLED(log, xbt_log_priority_debug)) {
765       char *buf, *res = NULL;
766       xbt_log_category_t cpp = category->parent->firstChild;
767       while (cpp) {
768         if (res) {
769           buf = bprintf("%s %s", res, cpp->name);
770           free(res);
771           res = buf;
772         } else {
773           res = xbt_strdup(cpp->name);
774         }
775         cpp = cpp->nextSibling;
776       }
777
778       XBT_DEBUG("Childs of %s: %s; nextSibling: %s",
779              category->parent->name, res,
780              (category->parent->nextSibling ?
781               category->parent->nextSibling->name : "none"));
782
783       free(res);
784     }
785
786   }
787
788   /* Apply the control */
789   if (xbt_log_settings) {
790     xbt_assert(category, "NULL category");
791     xbt_assert(category->name);
792
793     xbt_dynar_foreach(xbt_log_settings, cursor, setting) {
794       xbt_assert(setting, "Damnit, NULL cat in the list");
795       xbt_assert(setting->catname, "NULL setting(=%p)->catname",
796                  (void *) setting);
797
798       if (!strcmp(setting->catname, category->name)) {
799         found = 1;
800         _xbt_log_cat_apply_set(category, setting);
801         xbt_dynar_cursor_rm(xbt_log_settings, &cursor);
802       }
803     }
804
805     if (!found)
806       XBT_DEBUG("Category '%s': inherited threshold = %s (=%d)",
807                 category->name, xbt_log_priority_names[category->threshold],
808                 category->threshold);
809   }
810
811   category->initialized = 1;
812   if (log_cat_init_mutex != NULL) {
813     xbt_os_rmutex_release(log_cat_init_mutex);
814   }
815   return priority >= category->threshold;
816
817 #undef _xbt_log_cat_init
818 }
819
820 void xbt_log_parent_set(xbt_log_category_t cat, xbt_log_category_t parent)
821 {
822   xbt_assert(cat, "NULL category to be given a parent");
823   xbt_assert(parent, "The parent category of %s is NULL", cat->name);
824
825   /* if the category is initialized, unlink from current parent */
826   if (cat->initialized) {
827
828     xbt_log_category_t *cpp = &cat->parent->firstChild;
829
830     while (*cpp != cat && *cpp != NULL) {
831       cpp = &(*cpp)->nextSibling;
832     }
833
834     xbt_assert(*cpp == cat);
835     *cpp = cat->nextSibling;
836   }
837
838   cat->parent = parent;
839   cat->nextSibling = parent->firstChild;
840
841   parent->firstChild = cat;
842
843   if (!parent->initialized)
844     _xbt_log_cat_init(parent, xbt_log_priority_uninitialized /* ignored */ );
845
846   cat->threshold = parent->threshold;
847
848   cat->isThreshInherited = 1;
849 }
850
851 static void _set_inherited_thresholds(xbt_log_category_t cat)
852 {
853
854   xbt_log_category_t child = cat->firstChild;
855
856   for (; child != NULL; child = child->nextSibling) {
857     if (child->isThreshInherited) {
858       if (cat != &_XBT_LOGV(log))
859         XBT_VERB("Set category threshold of %s to %s (=%d)",
860               child->name, xbt_log_priority_names[cat->threshold],
861               cat->threshold);
862       child->threshold = cat->threshold;
863       _set_inherited_thresholds(child);
864     }
865   }
866
867
868 }
869
870 void xbt_log_threshold_set(xbt_log_category_t cat,
871                            e_xbt_log_priority_t threshold)
872 {
873   cat->threshold = threshold;
874   cat->isThreshInherited = 0;
875
876   _set_inherited_thresholds(cat);
877
878 }
879
880 static xbt_log_setting_t _xbt_log_parse_setting(const char *control_string)
881 {
882
883   xbt_log_setting_t set = xbt_new(s_xbt_log_setting_t, 1);
884   const char *name, *dot, *eq;
885
886   set->catname = NULL;
887   set->thresh = xbt_log_priority_uninitialized;
888   set->fmt = NULL;
889   set->additivity = -1;
890   set->appender = NULL;
891
892   if (!*control_string)
893     return set;
894   XBT_DEBUG("Parse log setting '%s'", control_string);
895
896   control_string += strspn(control_string, " ");
897   name = control_string;
898   control_string += strcspn(control_string, ".= ");
899   dot = control_string;
900   control_string += strcspn(control_string, ":= ");
901   eq = control_string;
902   control_string += strcspn(control_string, " ");
903
904   xbt_assert(*dot == '.' && (*eq == '=' || *eq == ':'),
905               "Invalid control string '%s'", control_string);
906
907   if (!strncmp(dot + 1, "thresh", (size_t) (eq - dot - 1))) {
908     int i;
909     char *neweq = xbt_strdup(eq + 1);
910     char *p = neweq - 1;
911
912     while (*(++p) != '\0') {
913       if (*p >= 'a' && *p <= 'z') {
914         *p -= 'a' - 'A';
915       }
916     }
917
918     XBT_DEBUG("New priority name = %s", neweq);
919     for (i = 0; i < xbt_log_priority_infinite; i++) {
920       if (!strncmp(xbt_log_priority_names[i], neweq, p - eq)) {
921         XBT_DEBUG("This is priority %d", i);
922         break;
923       }
924     }
925     if (i < xbt_log_priority_infinite) {
926       set->thresh = (e_xbt_log_priority_t) i;
927     } else {
928       THROWF(arg_error, 0,
929              "Unknown priority name: %s (must be one of: trace,debug,verbose,info,warning,error,critical)",
930              eq + 1);
931     }
932     free(neweq);
933   } else if (!strncmp(dot + 1, "add", (size_t) (eq - dot - 1)) ||
934              !strncmp(dot + 1, "additivity", (size_t) (eq - dot - 1))) {
935
936     char *neweq = xbt_strdup(eq + 1);
937     char *p = neweq - 1;
938
939     while (*(++p) != '\0') {
940       if (*p >= 'a' && *p <= 'z') {
941         *p -= 'a' - 'A';
942       }
943     }
944     if (!strcmp(neweq, "ON") || !strcmp(neweq, "YES")
945         || !strcmp(neweq, "1")) {
946       set->additivity = 1;
947     } else {
948       set->additivity = 0;
949     }
950     free(neweq);
951   } else if (!strncmp(dot + 1, "app", (size_t) (eq - dot - 1)) ||
952              !strncmp(dot + 1, "appender", (size_t) (eq - dot - 1))) {
953
954     char *neweq = xbt_strdup(eq + 1);
955
956     if (!strncmp(neweq, "file:", 5)) {
957       set->appender = xbt_log_appender_file_new(neweq + 5);
958     } else {
959       THROWF(arg_error, 0, "Unknown appender log type: '%s'", neweq);
960     }
961     free(neweq);
962   } else if (!strncmp(dot + 1, "fmt", (size_t) (eq - dot - 1))) {
963     set->fmt = xbt_strdup(eq + 1);
964   } else {
965     char buff[512];
966     snprintf(buff, min(512, eq - dot), "%s", dot + 1);
967     THROWF(arg_error, 0, "Unknown setting of the log category: '%s'",
968            buff);
969   }
970   set->catname = (char *) xbt_malloc(dot - name + 1);
971
972   memcpy(set->catname, name, dot - name);
973   set->catname[dot - name] = '\0';      /* Just in case */
974   XBT_DEBUG("This is for cat '%s'", set->catname);
975
976   return set;
977 }
978
979 static xbt_log_category_t _xbt_log_cat_searchsub(xbt_log_category_t cat,
980                                                  char *name)
981 {
982   xbt_log_category_t child, res;
983
984   XBT_DEBUG("Search '%s' into '%s' (firstChild='%s'; nextSibling='%s')", name,
985          cat->name, (cat->firstChild ? cat->firstChild->name : "none"),
986          (cat->nextSibling ? cat->nextSibling->name : "none"));
987   if (!strcmp(cat->name, name))
988     return cat;
989
990   for (child = cat->firstChild; child != NULL; child = child->nextSibling) {
991     XBT_DEBUG("Dig into %s", child->name);
992     res = _xbt_log_cat_searchsub(child, name);
993     if (res)
994       return res;
995   }
996
997   return NULL;
998 }
999
1000 /**
1001  * \ingroup XBT_log
1002  * \param control_string What to parse
1003  *
1004  * Typically passed a command-line argument. The string has the syntax:
1005  *
1006  *      ( [category] "." [keyword] ":" value (" ")... )...
1007  *
1008  * where [category] is one the category names (see \ref XBT_log_cats for
1009  * a complete list of the ones defined in the SimGrid library)
1010  * and keyword is one of the following:
1011  *
1012  *    - thres: category's threshold priority. Possible values:
1013  *             TRACE,DEBUG,VERBOSE,INFO,WARNING,ERROR,CRITICAL
1014  *    - add or additivity: whether the logging actions must be passed to
1015  *      the parent category.
1016  *      Possible values: 0, 1, no, yes, on, off.
1017  *      Default value: yes.
1018  *    - fmt: the format to use. See \ref log_use_conf_fmt for more information.
1019  *    - app or appender: the appender to use. See \ref log_use_conf_app for more
1020  *      information.
1021  *
1022  */
1023 void xbt_log_control_set(const char *control_string)
1024 {
1025   xbt_log_setting_t set;
1026
1027   /* To split the string in commands, and the cursors */
1028   xbt_dynar_t set_strings;
1029   char *str;
1030   unsigned int cpt;
1031
1032   if (!control_string)
1033     return;
1034   XBT_DEBUG("Parse log settings '%s'", control_string);
1035
1036   /* Special handling of no_loc request, which asks for any file localization to be omitted (for tesh runs) */
1037   if (!strcmp(control_string, "no_loc")) {
1038     xbt_log_no_loc = 1;
1039     return;
1040   }
1041   /* some initialization if this is the first time that this get called */
1042   if (xbt_log_settings == NULL)
1043     xbt_log_settings = xbt_dynar_new(sizeof(xbt_log_setting_t),
1044                                      _free_setting);
1045
1046   /* split the string, and remove empty entries */
1047   set_strings = xbt_str_split_quoted(control_string);
1048
1049   if (xbt_dynar_is_empty(set_strings)) {     /* vicious user! */
1050     xbt_dynar_free(&set_strings);
1051     return;
1052   }
1053
1054   /* Parse each entry and either use it right now (if the category was already
1055      created), or store it for further use */
1056   xbt_dynar_foreach(set_strings, cpt, str) {
1057     xbt_log_category_t cat = NULL;
1058
1059     set = _xbt_log_parse_setting(str);
1060     cat =
1061         _xbt_log_cat_searchsub(&_XBT_LOGV(XBT_LOG_ROOT_CAT), set->catname);
1062
1063     if (cat) {
1064       XBT_DEBUG("Apply directly");
1065       _xbt_log_cat_apply_set(cat, set);
1066       _free_setting((void *) &set);
1067     } else {
1068
1069       XBT_DEBUG("Store for further application");
1070       XBT_DEBUG("push %p to the settings", (void *) set);
1071       xbt_dynar_push(xbt_log_settings, &set);
1072     }
1073   }
1074   xbt_dynar_free(&set_strings);
1075 }
1076
1077 void xbt_log_appender_set(xbt_log_category_t cat, xbt_log_appender_t app)
1078 {
1079   if (cat->appender) {
1080     if (cat->appender->free_)
1081       cat->appender->free_(cat->appender);
1082     free(cat->appender);
1083   }
1084   cat->appender = app;
1085 }
1086
1087 void xbt_log_layout_set(xbt_log_category_t cat, xbt_log_layout_t lay)
1088 {
1089 #define _xbt_log_cat_init(a, b) (0)
1090   if (!cat->appender) {
1091     XBT_VERB
1092         ("No appender to category %s. Setting the file appender as default",
1093          cat->name);
1094     xbt_log_appender_set(cat, xbt_log_appender_file_new(NULL));
1095   }
1096   if (cat->layout) {
1097     if (cat->layout->free_) {
1098       cat->layout->free_(cat->layout);
1099     }
1100     free(cat->layout);
1101   }
1102   cat->layout = lay;
1103   xbt_log_additivity_set(cat, 0);
1104 #undef _xbt_log_cat_init
1105 }
1106
1107 void xbt_log_additivity_set(xbt_log_category_t cat, int additivity)
1108 {
1109   cat->additivity = additivity;
1110 }