Logo AND Algorithmique Numérique Distribuée

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