File: introduction.dox

package info (click to toggle)
log4cxx 0.9.7-6
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 4,620 kB
  • ctags: 2,766
  • sloc: cpp: 18,909; sh: 8,867; xml: 1,146; makefile: 480; ansic: 159
file content (921 lines) | stat: -rwxr-xr-x 36,013 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
/** 
@page Introduction Short introduction to log4cxx

This document is largely inspired of the
<a href=http://logging.apache.org/log4j/docs/manual.html>Short introduction to
log4j</a> by <i>Ceki Glc</i>

@section Contents
- @ref Abstract
- @ref IntroductionIntroduction
- @ref LoggersAppendersAndLayouts
	- @ref LoggerHierarchy
	- @ref AppendersAndLayouts
	.
- @ref Configuration
- @ref DefaultInitializationProcedure
- @ref NDC
- @ref Performance
- @ref Conclusion

@section Abstract

This document describes the log4cxx API, its unique features and design
rationale. Log4cxx is an open source project based on the work of several
authors. It allows the developer to control which log statements are output
with arbitrary granularity. It is fully configurable at runtime using external
configuration files. Best of all, log4cxx has a gentle learning curve. Beware:
 judging from user feedback, it is also quite addictive.
 
@section IntroductionIntroduction Introduction

The log4cxx framework is based on log4j, see http://logging.apache.org/log4j
for more information on log4cxx.

The package is distributed under the 
<a href=http://logging.apache.org/log4j/LICENSE.txt>Apache Software License
</a>, a fully-fledged open source license certified by the 
<a href=http://www.opensource.org/> open source</a> initiative. The latest
log4cxx version, including full-source code, class files and documentation can
be found at http://logging.apache.org/log4cxx .

Almost every large application includes its own logging or tracing API.
Inserting log statements into code is a low-tech method for debugging it.
It may also be the only way because debuggers are not always available or
applicable. This is usually the case for multithreaded applications and
distributed applications at large.

Experience indicates that logging was an important component of the development
cycle. It offeres several advantages. It provides precise context about a run
of the application. Once inserted into the code, the generation of logging
output requires no human intervention. Moreover, log output can be saved in
persistent medium to be studied at a later time. In addition to its use in the
development cycle, a sufficiently rich logging package can also be viewed as an
auditing tool.

Logging does have its drawbacks. It can slow down an application. If too
verbose, it can cause scrolling blindness. To alleviate these concerns,
log4cxx is designed to be reliable, fast and extensible. Since logging is
rarely the main focus of an application, the log4cxx API strives to be simple
to understand and to use.

@section LoggersAppendersAndLayouts Loggers, Appenders and Layouts

Log4cxx has three main components: loggers, appenders and layouts. These three
types of components work together to enable developers to log messages
according to message type and level, and to control at runtime how these
messages are formatted and where they are reported.

@subsection LoggerHierarchy Logger hierarchy

The first and foremost advantage of any logging API over plain std::cout
resides in its ability to disable certain log statements while allowing others
to print unhindered. This capability assumes that the logging space, that is,
the space of all possible logging statements, is categorized according to some
developer-chosen criteria.

Loggers are named entities. Logger names are case-sensitive and they follow the
hierarchical naming rule:

<table bgcolor="#EEEE99">
<tr>
<td>
<dl>
<dt><b>Named Hierarchy</b>
<dd><p>A logger is said to be an <em>ancestor</em> of another
logger if its name followed by a dot is a prefix of the
<em>descendant</em> logger name. A logger is said to be a
<em>parent</em> of a <em>child</em> logger if there are no
ancestors between itself and the descendant logger.
</dl>
</table>

For example, the logger named <code>com.foo</code> is a parent of the logger
named <code>com.foo.Bar</code>. Similarly, <code>cpp</code> is a parent of
<code>cpp.util</code> and an ancestor of <code>cpp.util.Vector</code>.
This naming scheme should be familiar to most developers.

The root logger resides at the top of the logger hierarchy. It is exceptional
in two ways:

-# it always exists,
-# it cannot be retrieved by name. 

Invoking the class static log4cxx::Logger::getRootLogger method retrieves it.
All other loggers are instantiated and retrieved with the class static
log4cxx::Logger::getLogger method. This method takes the name of the desired
logger as a parameter.Some of the basic methods in the Logger class are listed
below.

@code
#include <log4cxx/logger.h>

class Logger
{
public:
    // Creation & retrieval methods:
    static LoggerPtr getRootLogger();
    static LoggerPtr getLogger(const String& name);

    // printing methods:
    void debug(const String& message);
    void info(const String& message);
    void warn(const String& message);
    void error(const String& message);
    void fatal(const String& message);

    // generic printing method:
    void log(const LevelPtr& l, const String& message);
};
@endcode

Loggers may be assigned levels. The set of possible levels, that is {@link 
log4cxx::Level::DEBUG DEBUG}, {@link log4cxx::Level::INFO INFO}, {@link
log4cxx::Level::WARN WARN}, {@link log4cxx::Level::ERROR ERROR} and {@link
log4cxx::Level::FATAL FATAL} are defined in the log4cxx::Level class. Although
we do not encourage you to do so, you may define your own levels by
sub-classing the Level class. A perhaps better approach will be explained later
on.

If a given logger is not assigned a level, then it inherits one from its closest
ancestor with an assigned level. More formally:

<table bgcolor="#EEEE99">
<tr>
<td>
<dl>
<dt><b>Level Inheritance</b>
<dd><p>The <em>inherited level</em> for a given logger
<i>C</i>, is equal to the first non-null level in the logger
hierarchy, starting at <i>C</i> and proceeding upwards in the
hierarchy towards the <code>root</code> logger.
</dl>
</table>

To ensure that all loggers can eventually inherit a level, the root logger
 always has an assigned level.

Below are four tables with various assigned level values and the resulting
inherited levels according to the above rule. 

<table border="1" >
  <caption align=bottom>Example 1</caption>
  <tr><th>Logger<br>name</th><th>Assigned<br>level</th>
    <th>Inherited<br>level</th></tr>
    <tr align=left><td>root</td>    <td>Proot</td> <td>Proot</td></tr>
    <tr align=left><td>X </td>      <td>none</td>  <td>Proot</td></tr>
    <tr align=left><td>X.Y </td>    <td>none</td>  <td>Proot</td></tr>
    <tr align=left><td>X.Y.Z</td>   <td>none</td>  <td>Proot</td></tr>
</table>

In example 1 above, only the root logger is assigned a
level. This level value, <code>Proot</code>, is inherited by the
other loggers <code>X</code>, <code>X.Y</code> and
<code>X.Y.Z</code>.

<table border="1">
    <caption align=bottom>Example 2</caption>
    <tr><th>Logger<br>name</th><th>Assigned<br>level</th>

    <th>Inherited<br>level</th></tr>
    <tr align=left><td>root</td>    <td>Proot</td> <td>Proot</td></tr>
    <tr align=left><td>X </td>      <td>Px</td>    <td>Px</td></tr>

    <tr align=left><td>X.Y </td>    <td>Pxy</td>   <td>Pxy</td></tr>
    <tr align=left><td>X.Y.Z</td>   <td>Pxyz</td>  <td>Pxyz</td></tr>
</table>

In example 2, all loggers have an assigned level value. There
is no need for level inheritence.

<table border="1">
    <caption align=bottom>Example 3</caption>
    <tr><th>Logger<br>name</th><th>Assigned<br>level</th>
    <th>Inherited<br>level</th></tr>
    <tr align=left><td>root</td>    <td>Proot</td> <td>Proot</td></tr>

    <tr align=left><td>X </td>      <td>Px</td>    <td>Px</td></tr>
    <tr align=left><td>X.Y </td>    <td>none</td>  <td>Px</td></tr>
    <tr align=left><td>X.Y.Z</td>   <td>Pxyz</td>  <td>Pxyz</td></tr>
</table>

In example 3, the loggers <code>root</code>, <code>X</code> and
<code>X.Y.Z</code> are assigned the levels <code>Proot</code>,
<code>Px</code> and <code>Pxyz</code> respectively. The logger
<code>X.Y</code> inherits its level value from its parent
<code>X</code>.

<table border=1>
    <caption align=bottom>Example 4</caption>
    <tr><th>Logger<br>name</th><th>Assigned<br>level</th>
    <th>Inherited<br>level</th></tr>
    <tr align=left><td>root</td>    <td>Proot</td> <td>Proot</td></tr>

    <tr align=left><td>X </td>      <td>Px</td>    <td>Px</td></tr>
    <tr align=left><td>X.Y </td>    <td>none</td>  <td>Px</td></tr>
    <tr align=left><td>X.Y.Z</td>   <td>none</td>  <td>Px</td></tr>
</table>

In example 4, the loggers <code>root</code> and <code>X</code>
and are assigned the levels <code>Proot</code> and <code>Px</code>
respectively. The loggers <code>X.Y</code> and <code>X.Y.Z</code>
inherits their level value from their nearest parent <code>X</code>
having an assigned level..

Logging requests are made by invoking one of the printing methods
of a logger instance. These printing methods are {@link log4cxx::Logger::debug
debug}, {@link log4cxx::Logger::info info}, {@link log4cxx::Logger::warn
warn}, {@link log4cxx::Logger::error error}, {@link log4cxx::Logger::fatal
fatal} and {@link log4cxx::Logger::log log}.

By definition, the printing method determines the level of a
logging request. For example, if <code>c</code> is a logger
instance, then the statement <code>c.info("..")</code> is a logging
request of level INFO.

A logging request is said to be <em>enabled</em> if its level is
higher than or equal to the level of its logger. Otherwise, the
request is said to be <em>disabled</em>. A logger without an
assigned level will inherit one from the hierarchy. This rule is
summarized below.

<a name="selectionRule"><table bgcolor="#EEEE99">
<tr>
<td>
<dl>
<dt><b>Basic Selection Rule</b>
<dd><p>A log request of level <i>p</i> in a logger with
(either assigned or inherited, whichever is appropriate) level <i>q</i>, is enabled if <i> p &gt;=
q</i>.
</dl>
</table>

This rule is at the heart of log4cxx. It assumes that levels are ordered. For
the standard levels, we have DEBUG < INFO < WARN < ERROR < FATAL.

Here is an example of this rule. 

@code
// get a logger instance named "com.foo"
LoggerPtr logger = Logger::getLogger(_T("com.foo"));

// Now set its level. Normally you do not need to set the
// level of a logger programmatically. This is usually done
// in configuration files.
logger->setLevel(Level::INFO);

LoggerPtr barlogger = Logger::getLogger(_T("com.foo.Bar"));

// This request is enabled, because WARN >= INFO.
logger->warn(_T("Low fuel level."));

// This request is disabled, because DEBUG < INFO.
logger->debug(_T("Starting search for nearest gas station."));

// The logger instance barlogger, named "com.foo.Bar",
// will inherit its level from the logger named
// "com.foo" Thus, the following request is enabled
// because INFO >= INFO.
barlogger->info(_T("Located nearest gas station."));

// This request is disabled, because DEBUG < INFO.
barlogger->debug(_T("Exiting gas station search"));
@endcode

Calling the <code>getLogger</code> method with the same name will
always return a reference to the exact same logger object.

For example, in
@code
LoggerPtr x = Logger::getLogger("wombat");
LoggerPtr y = Logger::getLogger("wombat");
@endcode
<code>x</code> and <code>y</code> refer to <em>exactly</em> the same
logger object.

Thus, it is possible to configure a logger and then to retrieve
the same instance somewhere else in the code without passing around
references. In fundamental contradiction to biological parenthood,
where parents always preceed their children, log4cxx loggers can be
created and configured in any order. In particular, a "parent"
logger will find and link to its descendants even if it is
instantiated after them.

Configuration of the log4cxx environment is typically done at
application initialization. The preferred way is by reading a
configuration file. This approach will be discussed shortly.

Log4cxx makes it easy to name loggers by <em>software
component</em>.  This can be accomplished by statically instantiating
a logger in each class, with the logger name equal to the fully
qualified name of the class. This is a useful and straightforward
method of defining loggers. As the log output bears the name of the
generating logger, this naming strategy makes it easy to identify
the origin of a log message.  However, this is only one possible,
albeit common, strategy for naming loggers. Log4cxx does not restrict
the possible set of loggers. The developer is free to name the
loggers as desired.

Nevertheless, naming loggers after the class where they are
located seems to be the best strategy known so far.

@subsection AppendersAndLayouts Appenders and Layouts

The ability to selectively enable or disable logging requests based
on their logger is only part of the picture. Log4cxx allows logging
requests to print to multiple destinations. In log4cxx speak, an output
destination is called an <em>appender</em>. Currently, appenders exist
for the {@link log4cxx::ConsoleAppender console}, {@link 
log4cxx::FileAppender files}, GUI components, {@link 
log4cxx::net::SocketAppender remote socket} servers, {@link
log4cxx::nt::NTEventLogAppender NT Event Loggers}, and remote UNIX {@link
log4cxx::net::SyslogAppender Syslog} daemons. 
It is also possible to log {@link log4cxx::AsyncAppender asynchronously}.

More than one appender can be attached to a logger.

The {@link log4cxx::Logger::addAppender addAppender}
method adds an appender to a given logger.
<b>Each enabled logging
request for a given logger will be forwarded to all the appenders in
that logger as well as the appenders higher in the hierarchy.</b> In
other words, appenders are inherited additively from the logger
hierarchy. For example, if a console appender is added to the root
logger, then all enabled logging requests will at least print on the
console. If in addition a file appender is added to a logger, say
<em>C</em>, then enabled logging requests for <em>C</em> and
<em>C</em>'s children will print on a file <em>and</em> on the
console. It is possible to override this default behavior so that
appender accumulation is no longer additive by {@link 
log4cxx::Logger::setAdditivity setting
the additivity flag} to <code>false</code>.

The rules governing appender additivity are summarized below.

<a name="additivity"><table bgcolor="#EEEE99">
<tr>
<td>
<dl>
<dt><b>Appender Additivity</b>
<dd><p>The output of a log statement of logger <i>C</i> will
go to all the appenders in <i>C</i> and its ancestors. This is
the meaning of the term "appender additivity".
<p>However, if an ancestor of logger <i>C</i>, say <i>P</i>,
has the additivity flag set to <code>false</code>, then
<i>C</i>'s output will be directed to all the appenders in
<i>C</i> and it's ancestors upto and including <i>P</i> but
not the appenders in any of the ancestors of <i>P</i>.
<p>Loggers have their additivity flag set to
<code>true</code> by default.
</dl>
</table>

The table below shows an example:

<table align=center border=3 cellpadding=10>
  <tr rowspan="2">
  <th>Logger<br>Name <th>Added<br>Appenders <th>Additivity<br>Flag <th>Output Targets <th>Comment

<tr><td>root    <td>A1         <td>not applicable <td>A1

    <td>The root logger is anonymous but can be accessed with the
        Logger::getRootLogger() method. There is no default appender
        attached to root.


<tr><td>x       <td>A-x1, A-x2 <td>true <td>A1, A-x1, A-x2
    <td>Appenders of "x" and root.

<tr><td>x.y     <td>none       <td>true <td>A1, A-x1, A-x2
    <td>Appenders of "x" and root.

<tr><td>x.y.z   <td>A-xyz1     <td>true <td>A1, A-x1, A-x2, A-xyz1
    <td>Appenders in "x.y.z", "x" and root.

<tr><td>security        <td>A-sec	   <td>false

                                           <td>A-sec

    <td>No appender accumulation since the additivity flag is set to
        <code>false</code>.

<tr><td>security.access <td>none <td> true <td> A-sec <td>Only
    appenders of "security" because the additivity flag in "security" is
    set to <code>false</code>.

</table>

More often than not, users wish to customize not only the output
destination but also the output format. This is accomplished by
associating a <em>layout</em> with an appender. The layout is
responsible for formatting the logging request according to the user's
wishes, whereas an appender takes care of sending the formatted output
to its destination. The {@link
log4cxx::PatternLayout PatternLayout}, part
of the standard log4cxx distribution, lets the user specify the output
format according to conversion patterns similar to the C language
<code>printf</code> function.

For example, the PatternLayout with the conversion pattern "\%r [\%t]
\%-5p \%c - \%m\%n" will output something akin to:

<pre>176 [12345] INFO  org.foo.Bar - Located nearest gas station.
</pre>

The first field is the number of milliseconds elapsed since the
start of the program.  The second field is the identifier of the thread
making the log request.  The third field is the level of the log statement.
The fourth field is the name of the logger associated with the log
request. The text after the '-' is the message of the statement.

@section Configuration

Inserting log requests into the application code requires a fair
amount of planning and effort. Observation shows that approximately 4
percent of code is dedicated to logging. Consequently, even moderately
sized applications will have thousands of logging statements embedded
within their code.  Given their number, it becomes imperative to
manage these log statements without the need to modify them manually.

The log4cxx environment is fully configurable programmatically.
However, it is far more flexible to configure log4cxx using
configuration files.  Currently, configuration files can be written in
XML or in properties (key=value) format.

<p>Let us give a taste of how this is done with the help of an
imaginary application <code>MyApp</code> that uses log4cxx.

@code
// file MyApp.cpp

#include "com/foo/bar.h";
using namespace com::foo;

// include log4cxx header files.
#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/helpers/exception.h>

using namespace log4cxx;
using namespace log4cxx::helpers;

// Define a static logger variable so that it references the
// Logger instance named "MyApp".
LoggerPtr logger = Logger::getLogger(_T("MyApp"));

int main(int argc, char **argv)
{
	int result = EXIT_SUCCESS;
	try
	{
		// Set up a simple configuration that logs on the console.
		BasicConfigurator::configure();

		logger->info(_T("Entering application."));
		Bar bar;
		bar.doIt();
		logger->info(_T("Exiting application."));
	}
	catch(Exception&)
	{
		result = EXIT_FAILURE;
	}

	return result;
}
@endcode

<code>MyApp</code> begins by including log4cxx related headers.  It
then defines a static logger variable with the name
<code>MyApp</code> which happens to be the fully qualified name of the
class.

<code>MyApp</code> uses the <code>Bar</code> class defined in the
header file <code>com/foo/bar.h</code> and the source file <code>bar.cpp</code>.

@code
// file <com/foo/bar.h>

#include <log4cxx/logger.h>;

namespace com
{
	namespace foo
	{
		class Bar
		{
			static log4cxx::LoggerPtr logger;

		public:
			void doIt();
		};
	};
};
@endcode

@code
// file <bar.cpp>

#include "com/foo/bar.h"

using namespace com::foo;
using namespace log4cxx;

LoggerPtr Bar::logger = Logger::getLogger(_T("com.foo.bar"));

void Bar::doIt()
{
	logger->debug(_T("Did it again!"));
}
@endcode


The invocation of the {@link log4cxx::BasicConfigurator::configure
BasicConfigurator::configure} method creates a rather simple log4cxx setup.
This method is hardwired to add to the root logger {@link 
log4cxx::ConsoleAppender ConsoleAppender}. The output will be formatted using a
{@link  log4cxx::PatternLayout PatternLayout} set
to the pattern "\%-4r [\%t] \%-5p \%c \%x - \%m\%n".

Note that by default, the root logger is assigned to <code>Level::DEBUG</code>.

The output of MyApp is:
<pre>0    [12345] INFO  MyApp  - Entering application.
36   [12345] DEBUG com.foo.Bar  - Did it again!
51   [12345] INFO  MyApp  - Exiting application.
</pre>

As a side note, let me mention that in log4cxx child loggers link
only to their existing ancestors. In particular, the logger named
<code>com.foo.Bar</code> is linked directly to the <code>root</code>
logger, thereby circumventing the unused <code>com</code> or
<code>com.foo</code> loggers. This significantly increases
performance and reduces log4cxx's memory footprint.

The <code>MyApp</code> class configures log4cxx by invoking
<code>BasicConfigurator::configure</code> method.  Other classes only
need to include the <code><log4cxx/logger.h></code> header file,
retrieve the loggers they wish to use, and log away.

The previous example always outputs the same log information.
Fortunately, it is easy to modify <code>MyApp</code> so that the log
output can be controlled at run-time. Here is a slightly modified
version.

@code
// file MyApp2.cpp

#include "com/foo/bar.h";
using namespace com::foo;

// include log4cxx header files.
#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/exception.h>

using namespace log4cxx;
using namespace log4cxx::helpers;

// Define a static logger variable so that it references the
// Logger instance named "MyApp".
LoggerPtr logger = Logger::getLogger(_T("MyApp"));

int main(int argc, char **argv)
{
	int result = EXIT_SUCCESS;
	try
	{
		if (argc > 1)
		{
			// BasicConfigurator replaced with PropertyConfigurator.
			USES_CONVERSION;
			String propertyFileName = A2W(argv[1]);
			PropertyConfigurator::configure(propertyFileName);
		}
		else
		{
			BasicConfigurator::configure();
		}

		logger->info(_T("Entering application."));
		Bar bar
		bar.doIt();
		logger->info(_T("Exiting application."));
	}
	catch(Exception&)
	{
		result = EXIT_FAILURE;
	}

	return result;
}
@endcode

This version of <code>MyApp</code> instructs
<code>PropertyConfigurator</code> to parse a configuration file and
set up logging accordingly.

Here is a sample configuration file that results in exactly same
output as the previous <code>BasicConfigurator</code> based example.

<p><table bgcolor="CCAAAA"><tr><td>
<pre># Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=\%-4r [\%t] \%-5p \%c \%x - \%m\%n
</pre>
</table>

It can be noticed that the PropertyConfigurator file format is the same as in log4j.

Suppose we are no longer interested in seeing the output of any
component belonging to the <code>com::foo</code> namespace. The following
configuration file shows one possible way of achieving this.

<table bgcolor="CCAAAA"><tr><td>
<pre>log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout

# <strong>Print the date in ISO 8601 format</strong>
log4j.appender.A1.layout.ConversionPattern=<strong>\%d</strong> [\%t] \%-5p \%c - \%m\%n

# Print only messages of level WARN or above in the namespace com::foo.
<strong>log4j.logger.com.foo=WARN</strong>
</pre>
</table>

The output of <code>MyApp</code> configured with this file is shown below.

<pre><strong>2000-09-07 14:07:41,508</strong> [12345] INFO  MyApp - Entering application.
<strong>2000-09-07 14:07:41,529</strong> [12345] INFO  MyApp - Exiting application.
</pre>

As the logger <code>com.foo.Bar</code> does not have an assigned
level, it inherits its level from <code>com.foo</code>, which
was set to WARN in the configuration file. The log statement from the
<code>Bar::doIt</code> method has the level DEBUG, lower than the
logger level WARN. Consequently, <code>doIt()</code> method's log
request is suppressed.

Here is another configuration file that uses multiple appenders.

<table bgcolor="CCAAAA"><tr><td>
<pre>log4j.rootLogger=debug, <strong>stdout, R</strong>

log4j.appender.<strong>stdout</strong>=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] <strong>(%F:%L)</strong> - %m%n

log4j.appender.<strong>R</strong>=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log

log4j.appender.R.MaxFileSize=<strong>100KB</strong>

# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
</pre>
</table>

Calling the enhanced MyApp with the this configuration file will
output the following on the console.

<pre> INFO [main] <strong>(MyApp2.cpp:31)</strong> - Entering application.
DEBUG [main] <strong>(Bar.h:16)</strong> - Doing it again!
 INFO [main] <strong>(MyApp2.cpp:34)</strong> - Exiting application.
</pre>

In addition, as the root logger has been allocated a second
appender, output will also be directed to the <code>example.log</code>
file. This file will be rolled over when it reaches 100KB. When
roll-over occurs, the old version of <code>example.log</code> is
automatically moved to <code>example.log.1</code>.

Note that to obtain these different logging behaviors we did not
need to recompile code. We could just as easily have logged to a UNIX
Syslog daemon, redirected all <code>com.foo</code> output to an NT
Event logger, or forwarded logging events to a remote log4cxx server,
which would log according to local server policy, for example by
forwarding the log event to a second log4cxx server.

@section DefaultInitializationProcedure Default Initialization Procedure

The log4cxx library does not make any assumptions about its
environment. In particular, there are no default log4cxx
appenders. Under certain well-defined circumstances however, the
initialization of the logger hierarchy will attempt to
automatically configure log4cxx. 

The exact default initialization algorithm is defined as follows:

-# Set the <code>configurationOptionStr</code> string variable to the value of
the <b>log4j.configuration</b> environment variable.  <em>The preferred
way to specify the default initialization file is through the
<b>log4j.configuration</b> environment variable.</em> In case the environment
variable <b>log4j.configuration</b> is not defined, then set the
string variable <code>configurationOptionStr</code> to its default value
"log4j.properties".
@n @n
-# Attempt to convert the <code>configurationOptionStr</code> variable to a
valid file name.
@n @n
-# If no file could be found, abort default
initialization. Otherwise, configure log4cxx from the file name.
@n @n
The {@link log4cxx::PropertyConfigurator PropertyConfigurator}
will be used to parse the file to configure log4cxx unless the file name ends
with the ".xml" extension, in which case the {@link
log4cxx::xml::DOMConfigurator DOMConfigurator}
will be used. You can optionaly specify a custom configurator. The
value of the <b>log4j.configuratorClass</b> environment variable is taken
as the fully qualified class name of your custom configurator. The
custom configurator you specify <em>must</em> implement the {@link
log4cxx::spi::Configurator Configurator} interface. 

@section NDC Nested Diagnostic Contexts 

Most real-world systems have to deal with multiple clients
simultaneously. In a typical multithreaded implementation of such a
system, different threads will handle different clients. Logging is
especially well suited to trace and debug complex distributed
applications. A common approach to differentiate the logging output of
one client from another is to instantiate a new separate logger for
each client. This promotes the proliferation of loggers and
increases the management overhead of logging.

A lighter technique is to uniquely stamp each log request initiated
from the same client interaction. Neil Harrison described this method
in the book "Patterns for Logging Diagnostic Messages," in <em>Pattern
Languages of Program Design 3</em>, edited by R. Martin, D.  Riehle,
and F. Buschmann (Addison-Wesley, 1997).

To uniquely stamp each request, the
user pushes contextual information into the NDC, the abbreviation of
<em>Nested Diagnostic Context</em>. The NDC class is shown below.

@code
class NDC
{
public:
    // Used when printing the diagnostic
    static String get();

    // Remove the top of the context from the NDC.
    static String pop();

    // Add diagnostic context for the current thread.
    static void push(const String& message);

    // Remove the diagnostic context for this thread.
    static void remove();
 };
@endcode

The NDC is managed per thread as a <em>stack</em> of contextual
information. Note that all methods of the <code>log4cxx::NDC</code>
class are static. Assuming that NDC printing is turned on, every time
a log request is made, the appropriate log4cxx component will include
the <em>entire</em> NDC stack for the current thread in the log
output. This is done without the intervention of the user, who is
responsible only for placing the correct information in the NDC by
using the <code>push</code> and <code>pop</code> methods at a few
well-defined points in the code.  In contrast, the per-client logger
approach commands extensive changes in the code.

To illustrate this point, let us take the example of a server
delivering content to numerous clients. The server can build the NDC
at the very beginning of the request before executing other code. The
contextual information can be the client's host name and other
information inherent to the request, typically caller identity.
Hence, even if the server is serving multiple clients
simultaneously, the logs initiated by the same code, i.e. belonging to
the same logger, can still be distinguished because each client
request will have a different NDC stack. Contrast this with the
complexity of passing a freshly instantiated logger to all code
exercised during the client's request.

Nevertheless, some sophisticated applications, such as virtual
hosting web servers, must log differently depending on the virtual
host context and also depending on the software component issuing the
request. Recent log4cxx releases support multiple hierarchy trees. This
enhancement allows each virtual host to possess its own copy of the
logger hierarchy.

@section Performance

One of the often-cited arguments against logging is its
computational cost. This is a legitimate concern as even moderately
sized applications can generate thousands of log requests. Much
effort was spent measuring and tweaking logging performance. Log4cxx
claims to be fast and flexible: speed first, flexibility second.

The user should be aware of the following performance issues.

-# <b>Logging performance when logging is turned off.</b>
@n @n
When logging is turned
off entirely or just for a {@link log4cxx::Hierarchy::setThreshold
 set of levels}, the cost of a log request consists of a method
invocation plus an integer comparison.  On a 233 MHz Pentium II
machine this cost is typically in the 5 to 50 nanosecond range.
@n @n
However, The method invocation involves the "hidden" cost of
parameter construction.
@n @n
For example, for some logger <code>logger</code>, writing,
@code 
logger->debug("The user named [" + strName + "] is logged");
@endcode
incurs the cost of constructing the message parameter, i.e.
concatenating intermediate strings,
regardless of whether the message will be logged or not.
@n @n
This cost of parameter construction can be quite high and it
depends on the size of the parameters involved.
@n @n
To avoid the parameter construction cost write:
@code 
if(logger->isDebugEnabled()
{
	logger->forcedLog(Level::DEBUG, 
		"The user named [" + strName + "] is logged");
}
@endcode 
or in a simpler way:
@code 
LOG4CXX_DEBUG(logger, "The user named [" + strName + "] is logged");
@endcode
@n
Certain users resort to preprocessing or compile-time techniques to compile out
all log statements. This leads to perfect performance efficiency with respect
to logging. However, since the resulting application binary does not contain
any log statements, logging cannot be turned on for that binary. In my opinion
this is a disproportionate price to pay in exchange for a small performance
gain.
@n @n
-# <b>The performance of deciding whether to log or not to log when
logging is turned on.</b>
@n @n
This is essentially the performance of walking the logger
hierarchy. When logging is turned on, log4cxx still needs to compare
the level of the log request with the level of the request
logger. However, loggers may not have an assigned
level; they can inherit them from the logger hierarchy. Thus,
before inheriting a level, the logger may need to search its
ancestors.
@n @n
There has been a serious effort to make this hierarchy walk to
be as fast as possible. For example, child loggers link only to
their existing ancestors. In the <code>BasicConfigurator</code>
example shown earlier, the logger named <code>com.foo.Bar</code> is
linked directly to the root logger, thereby circumventing the
nonexistent <code>com</code> or <code>com.foo</code> loggers. This
significantly improves the speed of the walk, especially in "sparse"
hierarchies.
@n @n
The typical cost of walking the hierarchy is typically 3
times slower than when logging is turned off entirely.
@n @n
-# <b>Actually outputting log messages</b>
This is the cost of formatting the log output and sending it to
its target destination. Here again, a serious effort was made to
make layouts (formatters) perform as quickly as possible. The same
is true for appenders. The typical cost of actually logging is
about 100 to 300 microseconds.

Although log4cxx has many features, its first design goal was speed.
Some log4cxx components have been rewritten many times to improve
performance.  Nevertheless, contributors frequently come up with new
optimizations. You should be pleased to know that when configured with
the {@link log4cxx::SimpleLayout SimpleLayout}
performance tests have shown log4cxx to log as quickly as
<code>std::cout</code>.

@section Conclusion

Log4cxx is a popular logging package written in C++.  One of its
distinctive features is the notion of inheritance in loggers. Using
a logger hierarchy it is possible to control which log statements
are output at arbitrary granularity. This helps reduce the volume of
logged output and minimize the cost of logging.

One of the advantages of the log4cxx API is its manageability. Once
the log statements have been inserted into the code, they can be
controlled with configuration files. They can be selectively enabled
or disabled, and sent to different and multiple output targets in
user-chosen formats. The log4cxx package is designed so that log
statements can remain in shipped code without incurring a heavy
performance cost.
*/