Logo AND Algorithmique Numérique Distribuée

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