Logo AND Algorithmique Numérique Distribuée

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