Logo AND Algorithmique Numérique Distribuée

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