Linux

log4cplus使用指南 log4cplus配置文件编写及使用


否则说明阁下愿意支付以100元人民币每字计的稿费,敬请留意。

1.1 背景

本人使用log4cplus时喜欢采用配置文件的方式,这样非常的灵活;然而网上的资料对各配置没有完整的总结,且配置项是2010年前的,官方文档也没有对此进行完整归纳,本人通过阅读源代码,并和作者取得联系,将其中错误的配置项进行了bug提交,作者已经修正配置项问题。在此我将从代码中所有涉及到的配置选项都归总于该文,配置项的作用采用官方描述,使用英文,对英文不好的同学建议和1.2所给博文对照使用。默认值在选项后的括号中。

1.2 对照文章

注:这主要是方便大家了解log4cplus的使用方法,以及配置方法。对英文不好的同学也可用来对本文的参照。

log4cplus 使用方法 配置 - wclhjs的个人空间

见log4cplus\src\factory.cxx文件(摘录于log4cplus 1.2.x)

"blog_20141127_2_4197540" name="code" >
void initializeFactoryRegistry()
{
spi::AppenderFactoryRegistry& reg = spi::getAppenderFactoryRegistry();
DisableFactoryLocking<spi::AppenderFactoryRegistry> dfl_reg (reg);
LOG4CPLUS_REG_APPENDER (reg, ConsoleAppender);
LOG4CPLUS_REG_APPENDER (reg, NullAppender);
LOG4CPLUS_REG_APPENDER (reg, FileAppender);
LOG4CPLUS_REG_APPENDER (reg, RollingFileAppender);
LOG4CPLUS_REG_APPENDER (reg, DailyRollingFileAppender);
LOG4CPLUS_REG_APPENDER (reg, TimeBasedRollingFileAppender);log4cplus-1.2.x
LOG4CPLUS_REG_APPENDER (reg, SocketAppender);
#if defined(_WIN32)
# if defined(LOG4CPLUS_HAVE_NT_EVENT_LOG)
LOG4CPLUS_REG_APPENDER (reg, NTEventLogAppender);
# endif
# if defined(LOG4CPLUS_HAVE_WIN32_CONSOLE)
LOG4CPLUS_REG_APPENDER (reg, Win32ConsoleAppender);
# endif
LOG4CPLUS_REG_APPENDER (reg, Win32DebugAppender);
#endif
LOG4CPLUS_REG_APPENDER (reg, SysLogAppender);
#ifndef LOG4CPLUS_SINGLE_THREADED
LOG4CPLUS_REG_APPENDER (reg, AsyncAppender);
#endif
LOG4CPLUS_REG_APPENDER (reg, Log4jUdpAppender);
spi::LayoutFactoryRegistry& reg2 = spi::getLayoutFactoryRegistry();
DisableFactoryLocking<spi::LayoutFactoryRegistry> dfl_reg2 (reg2);
LOG4CPLUS_REG_LAYOUT (reg2, SimpleLayout);
LOG4CPLUS_REG_LAYOUT (reg2, TTCCLayout);
LOG4CPLUS_REG_LAYOUT (reg2, PatternLayout);
spi::FilterFactoryRegistry& reg3 = spi::getFilterFactoryRegistry();
DisableFactoryLocking<spi::FilterFactoryRegistry> dfl_reg3 (reg3);
LOG4CPLUS_REG_FILTER (reg3, DenyAllFilter);
LOG4CPLUS_REG_FILTER (reg3, LogLevelMatchFilter);
LOG4CPLUS_REG_FILTER (reg3, LogLevelRangeFilter);
LOG4CPLUS_REG_FILTER (reg3, StringMatchFilter);
spi::LocaleFactoryRegistry& reg4 = spi::getLocaleFactoryRegistry();
DisableFactoryLocking<spi::LocaleFactoryRegistry> dfl_reg4 (reg4);
LOG4CPLUS_REG_LOCALE (reg4, LOG4CPLUS_TEXT("GLOBAL"), spi::GlobalLocale);
LOG4CPLUS_REG_LOCALE (reg4, LOG4CPLUS_TEXT("DEFAULT"), spi::GlobalLocale);
LOG4CPLUS_REG_LOCALE (reg4, LOG4CPLUS_TEXT("USER"), spi::UserLocale);
LOG4CPLUS_REG_LOCALE (reg4, LOG4CPLUS_TEXT("CLASSIC"), spi::ClassicLocale);
}

3.1 Appender配置(appender.    log4cplus::xxxAppender)

3.1.1 Appender

"blog_20141127_3_774589" name="code" >
layout. (SimpleLayout)
This property specifies message layout used by Appender. \sa Layout
filters.
This property specifies possibly multiple filters used by Appender. Each of multple filters and its properties is under a numbered subkey of filters key. E.g.: filters.1=log4cplus::spi::LogLevelMatchFilter. Filter subkey numbers must be consecutive.
Threshold (NOT_SET_LOG_LEVEL)
This property specifies log level threshold. Events with lower log level than the threshold will not be logged by appender.
UseLockFile (false)
Set this property to true if you want your output through this appender to be synchronized between multiple processes. When this property is set to true then log4cplus uses OS specific facilities (e.g., lockf()) to provide inter-process locking. With the exception of FileAppender and its derived classes, it is also necessary to provide path to a lock file using the LockFile property. \sa FileAppender
LockFile
This property specifies lock file, file used for inter-process synchronization of log file access. The property is only used when UseLockFile is set to true. Then it is mandatory. \sa FileAppender

3.1.2 ConsoleAppender

"blog_20141127_4_7875024" name="code" >
logToStdErr (false)
When it is set true, the output stream will be std::cerr instead of std::cout.
ImmediateFlush (false)
When it is set true, output stream will be flushed after each appended event.

3.1.3 NullAppender

无配置项 

3.1.4 FileAppender (extends FileAppenderBase)

"blog_20141127_5_232734" name="code" >
File
This property specifies output file name.
ImmediateFlush (true)
When it is set true, output stream will be flushed after each appended event.
Append
When it is set true, output file will be appended to instead of being truncated at opening.
ReopenDelay (1)
This property sets a delay after which the appender will try to reopen log file again, after last logging failure. If reopenDelay is zero, each failed append operation will cause log file to be re-opened.
BufferSize (0)
Non-zero value of this property sets up buffering of output stream using a buffer of given size.
UseLockFile (false)
Set this property to true if you want your output to go into a log file shared by multiple processes. When this property is set to true then log4cplus uses OS specific facilities (e.g., lockf()) to provide inter-process file locking. \sa Appender
LockFile (File value add .lock)
This property specifies lock file, file used for inter-process synchronization of log file access. When this property is not specified, the value is derived from File property by addition of ".lock" suffix. The property is only used when UseLockFile is set to true. \sa Appender
Locale ("DEFAULT") (GLOBAL DEFAULT USER CLASSIC)
This property specifies a locale name that will be imbued into output stream. Locale can be specified either by system specific locale name, e.g., en_US.gbk, or by one of four recognized keywords: GLOBAL, DEFAULT (which is an alias for GLOBAL), USER and CLASSIC. When specified locale is not available, GLOBAL is used instead. It is possible to register additional locale keywords by registering an instance of spi::LocaleFactory in spi::LocaleFactoryRegistry. \sa spi::getLocaleFactoryRegistry()
CreateDirs (false)
Set this property to true if you want to create missing directories in path leading to log file and lock file.

3.1.5 RollingFileAppender extends FileAppender

"blog_20141127_6_8403340" name="code" >
MaxFileSize MB KB (10M)
This property specifies maximal size of output file. The value is in bytes. It is possible to use MB and KB suffixes to specify the value in megabytes or kilobytes instead.
MaxBackupIndex (1)
This property limits the number of backup output files; e.g. how many log.1, log.2 etc. files will be kept.

3.1.6 DailyRollingFileAppender extends FileAppender

"blog_20141127_7_9124846" name="code" >
Schedule (DAILY)
This property specifies rollover schedule. The possible values are MONTHLY, WEEKLY, DAILY, TWICE_DAILY, HOURLY and MINUTELY.
MaxBackupIndex (10)
This property limits how many backup files are kept per single logging period; e.g. how many log.2009-11-07.1, log.2009-11-07.2 etc. files are kept.

3.1.7 TimeBasedRollingFileAppender extends FileAppenderBase (log4cplus-1.2.x specific)

"blog_20141127_8_6781690" name="code" >
FilenamePattern ("%d.log")
The mandatory fileNamePattern property defines the name of the rolled-over (archived) log files. Its value should consist of the name of the file, plus a suitably placed %d conversion specifier. The %d conversion specifier may contain a date-and-time pattern as specified by the java's SimpleDateFormat. The rollover period is inferred from the value of fileNamePattern.
MaxHistory (10)
The optional maxHistory property controls the maximum number of archive files to keep, deleting older files.
CleanHistoryOnStart (false)
If set to true, archive removal will be executed on appender start up. By default this property is set to false.

3.1.8 SocketAppender

"blog_20141127_9_5518329" name="code" >
host
Remote host name to connect and send events to.
port (9998)
Port on remote host to send events to.
ServerName
Host name of event's origin prepended to each event.

3.1.9 NTEventLogAppender (_WIN32 LOG4CPLUS_HAVE_NT_EVENT_LOG)

"blog_20141127_10_7276986" name="code" >
server
log ("Application")
source

3.1.10 Win32ConsoleAppender (_WIN32 LOG4CPLUS_HAVE_WIN32_CONSOLE)

"blog_20141127_11_4061778" name="code" >
AllocConsole (true)
This boolean property specifies whether or not this appender will try to allocate new console using the AllocConsole() Win32 function.
logToStdErr (false)
When it is set true, the output will be into STD_ERROR_HANDLE instead of STD_OUTPUT_HANDLE.
TextColor (0)
See MSDN documentation for Character Attributes.

3.1.11 Win32DebugAppender (_WIN32)

无配置项

3.1.12 SysLogAppender

"blog_20141127_12_638826" name="code" >
ident
First argument to openlog(), a string that will be prepended to every message.
facility
Facility is used in combination with syslog level in first argument to syslog(). It can be one of the supported facility names (case insensitive), e.g. auth, authpriv, console, cron, daemon, ftp, kern, local0, ..., local7, lpr, mail, news, ntp, security, syslog, user, uucp etc.
host
Destination syslog host. When this property is specified, messages are sent using UDP to destination host, otherwise messages are logged to local syslog.
port (514)
Destination port of syslog service on host specified by the host property. The default value is port 514.
udp (true)
When the syslog is remote, this property picks the IP protocol. When the value is true, UDP is used. When the value is false, TCP is used. The default value is true.
note Messages sent to remote syslog using UDP are conforming to RFC5424. Messages sent to remote syslog using TCP are using octet counting as described in RFC6587.

3.1.13 AsyncAppender (#ifndef LOG4CPLUS_SINGLE_THREADED)

"blog_20141127_13_7248894" name="code" >
Appender
(Appender.)
QueueLimit (100)

3.1.14 Log4jUdpAppender

"blog_20141127_14_3510298" name="code" >
host | SyslogHost (localhost)
Remote host name to connect and send events to.
port (5000)
Port on remote host to send events to.

3.1.15 MSTTSAppender **

"blog_20141127_15_4755192" name="code" >
Volume (0) <=100
Rate (0) |Rate| <= 101
Async (false)
SpeakPunc (false)

3.1.16 CLFSAppender **

"blog_20141127_16_4005594" name="code" >
LogName
LogSize (512 * 1024)
BufferSize (1024 * 64)
3.2 Layout配置(layout.    log4cplus::xxxLayout)

3.2.1 SimpleLayout

详细说明:
SimpleLayout consists of the LogLevel of the log statement, followed by " - " and then the log message itself. For example,

"blog_20141127_16_4005594" name="code" >
DEBUG - Hello world

3.2.2 TTCCLayout

"blog_20141127_17_7202335" name="code" >
DateFormat
The time format depends on the DateFormat used.
Use_gmtime (false)
Use_gmtime to specify whether messages should be logged using localtime or gmtime.
ThreadPrinting (true)
CategoryPrefixing (true)
ContextPrinting (true)
There are also ThreadPrinting, CategoryPrefixing and ContextPrinting properties to turn on and off thread name,logger name and NDC context printing respectively.
详细说明:
TTCC layout format consists of time, thread, Logger and nested diagnostic context information, hence the name.

The time format depends on the DateFormat used. Use the Use_gmtime to specify whether messages should be logged usinglocaltime orgmtime.
There are also ThreadPrinting, CategoryPrefixing and ContextPrinting properties to turn on and off thread name, logger name and NDC context printing respectively.

Here is an example TTCCLayout output:

1 [0x60004dca0] WARN test.TestThread <> - Thread-3 TestThread.run()- Starting...
1 [0x60004dca0] TRACE SlowObject <thread-3 loop=""> - ENTER: SlowObject::doSomething()
2 [0x60004b030] INFO SlowObject <thread-0 loop=""> - Actually doing something...1, 2, 3, testing...DONE
2 [0x60004b130] INFO SlowObject <thread-1 loop=""> - Actually doing something...
2 [0x60004b030] TRACE SlowObject <thread-0 loop=""> - EXIT: SlowObject::doSomething()
2 [0x60004b030] TRACE SlowObject <thread-0 loop=""> - ENTER: SlowObject::doSomething()
3 [0x60004b130] INFO SlowObject <thread-1 loop=""> - Actually doing something...1, 2, 3, testing...DONE
3 [0x60004cad0] INFO SlowObject <thread-2 loop=""> - Actually doing something...
</thread-2></thread-1></thread-0></thread-0></thread-1></thread-0></thread-3>
The first field is the number of milliseconds elapsed since the start of the program.

The second field is the thread outputting the log statement. (The value is the same as that of the `t` formatter for PatternLayout.)

The third field is the LogLevel.

The fourth field is the logger to which the statement belongs.

The fifth field (just before the '-') is the nested diagnostic context. Note the nested diagnostic context may be empty as in the first two statements. The text after the '-' is the message of the statement.

3.2.3 PatternLayout

"blog_20141127_18_8206466" name="code" >
NDCMaxDepth (0)
This property limits how many deepest NDC components will be printed by %x specifier
Pattern(false)
ConversionPattern
This property specifies conversion pattern.
详细说明:
A flexible layout configurable with pattern string.

The goal of this class is to format a InternalLoggingEvent and return the results as a string. The results depend on theconversion pattern.

The conversion pattern is closely related to the conversion pattern of the printf function in C. A conversion pattern is composed of literal text and format control expressions calledconversion specifiers.

You are free to insert any literal text within the conversion pattern.

Each conversion specifier starts with a percent sign (%%) and is followed by optionalformat modifiers and aconversion character. The conversion character specifies the type of data, e.g. Logger, LogLevel, date, thread name. The format modifiers control such things as field width, padding, left and right justification. The following is a simple example.

Let the conversion pattern be `"%-5p [%t]: %m%n"` and assume that the log4cplus environment was set to use a PatternLayout. Then the statements

Logger root = Logger.getRoot();
LOG4CPLUS_DEBUG(root, "Message 1");
LOG4CPLUS_WARN(root, "Message 2");
would yield the output DEBUG [main]: Message 1
WARN [main]: Message 2
Note that there is no explicit separator between text and conversion specifiers. The pattern parser knows when it has reached the end of a conversion specifier when it reads a conversion character. In the example above the conversion specifier"%-5p" means the LogLevel of the logging event should be left justified to a width of five characters.

The recognized conversion characters are

Conversion Character

Effect

b

Used to output file name component of path name. E.g. main.cxx from path../../main.cxx.

c

Used to output the logger of the logging event. The logger conversion specifier can be optionally followed byprecision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the logger name will be printed. By default the logger name is printed in full.

For example, for the logger name "a.b.c" the pattern %c{2} will output "b.c".

d

Used to output the date of the logging event in UTC. The date conversion specifier may be followed by adate format specifier enclosed between braces. For example,%%d{%%H:%%M:%%s} or%%d{%%d %%b %%Y %%H:%%M:%%s}. If no date format specifier is given then%%d{%%d %%m %%Y %%H:%%M:%%s} is assumed. The Following format options are possible:

%%a -- Abbreviated weekday name

%%A -- Full weekday name

%%b -- Abbreviated month name

%%B -- Full month name

%%c -- Standard date and time string

%%d -- Day of month as a decimal(1-31)

%%H -- Hour(0-23)

%%I -- Hour(1-12)

%%j -- Day of year as a decimal(1-366)

%%m -- Month as decimal(1-12)

%%M -- Minute as decimal(0-59)

%%p -- Locale's equivalent of AM or PM

%%q -- milliseconds as decimal(0-999) -- Log4CPLUS specific

%%Q -- fractional milliseconds as decimal(0-999.999) -- Log4CPLUS specific

%%S -- Second as decimal(0-59)

%%U -- Week of year, Sunday being first day(0-53)

%%w -- Weekday as a decimal(0-6, Sunday being 0)

%%W -- Week of year, Monday being first day(0-53)

%%x -- Standard date string

%%X -- Standard time string

%%y -- Year in decimal without century(0-99)

%%Y -- Year including century as decimal

%%Z -- Time zone name

%% -- The percent sign

Lookup the documentation for the strftime() function found in the <ctime> header for more information.

D

Used to output the date of the logging event in local time. All of the above information applies.

E

Used to output the value of a given environment variable. The name of is supplied as an argument in brackets. If the variable does exist then empty string will be used. For example, the pattern%E{HOME} will output the contents of the HOME environment variable.

F

Used to output the file name where the logging request was issued. NOTE Unlike log4j, there is no performance penalty for calling this method.

h

Used to output the hostname of this system (as returned by gethostname(2)). NOTE The hostname is only retrieved once at initialization.

H

Used to output the fully-qualified domain name of this system (as returned by gethostbyname(2) for the hostname returned by gethostname(2)).NOTE The hostname is only retrieved once at initialization.

l

Equivalent to using "%F:%L" NOTE: Unlike log4j, there is no performance penalty for calling this method.

L

Used to output the line number from where the logging request was issued. NOTE: Unlike log4j, there is no performance penalty for calling this method.

m

Used to output the application supplied message associated with the logging event.

M

Used to output function name using __FUNCTION__ or similar macro.NOTE The__FUNCTION__ macro is not standard but it is common extension provided by all compilers (as of 2010). In case it is missing or in case this feature is disabled using theLOG4CPLUS_DISABLE_FUNCTION_MACRO macro, %M expands to an empty string.

n

Outputs the platform dependent line separator character or characters.

p

Used to output the LogLevel of the logging event.

r

Used to output miliseconds since program start of the logging event.

t

Used to output the thread ID of the thread that generated the logging event. (This is either `pthread_t` value returned by `pthread_self()` on POSIX platforms or thread ID returned by `GetCurrentThreadId()` on Windows.)

T

Used to output alternative name of the thread that generated the logging event.

i

Used to output the process ID of the process that generated the logging event.

x

Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event.

X

Used to output the MDC (mapped diagnostic context) associated with the thread that generated the logging event. It takes optional key parameter. Without the key paramter (%%X), it outputs the whole MDC map. With the key (%%X{key}), it outputs just the key's value.

"%%"

The sequence "%%" outputs a single percent sign.

By default the relevant information is output as is. However, with the aid of format modifiers it is possible to change the minimum field width, the maximum field width and justification.

The optional format modifier is placed between the percent sign and the conversion character.

The first optional format modifier is the left justification flag which is just the minus (-) character. Then comes the optionalminimum field width modifier. This is a decimal constant that represents the minimum number of characters to output. If the data item requires fewer characters, it is padded on either the left or the right until the minimum width is reached. The default is to pad on the left (right justify) but you can specify right padding with the left justification flag. The padding character is space. If the data item is larger than the minimum field width, the field is expanded to accommodate the data. The value is never truncated.

This behavior can be changed using the maximum field width modifier which is designated by a period followed by a decimal constant. If the data item is longer than the maximum field, then the extra characters are removed from thebeginning of the data item and not from the end. For example, it the maximum field width is eight and the data item is ten characters long, then the first two characters of the data item are dropped. This behavior deviates from the printf function in C where truncation is done from the end.

Below are various format modifier examples for the logger conversion specifier.

Format modifier

left justify

minimum width

maximum width

comment

%20c

false

none

Left pad with spaces if the logger name is less than 20 characters long.

%-20c

true

none

Right pad with spaces if the logger name is less than 20 characters long.

%.30c

NA

none

Truncate from the beginning if the logger name is longer than 30 characters.

%20.30c

false

Left pad with spaces if the logger name is shorter than 20 characters. However, if logger name is longer than 30 characters, then truncate from the beginning.

%-20.30c

true

Right pad with spaces if the logger name is shorter than 20 characters. However, if logger name is longer than 30 characters, then truncate from the beginning.

Below are some examples of conversion patterns. "%r [%t] %-5p %c %x - %m%n" This is essentially the TTCC layout. "%-6r [%15.15t] %-5p %30.30c %x - %m%n" Similar to the TTCC layout except that the relative time is right padded if less than 6 digits, thread name is right padded if less than 15 characters and truncated if longer and the logger name is left padded if shorter than 30 characters and truncated if longer. The above text is largely inspired from Peter A. Darnell and Philip E. Margolis' highly recommended book "C -- a Software Engineering Approach", ISBN 0-387-97389-3. 3.3 Filter配置(filters.n (n=1,2,3,...,n  处理顺序与序号相反,即n,n-1,n-2,...,1)    log4cplus::spi::xxxFilter)

3.3.1 DenyAllFilter

无配置项

3.3.2 LogLevelMatchFilter

"blog_20141127_19_4434850" name="code" >
AcceptOnMatch (false)
LogLevelToMatch

3.3.3 LogLevelRangeFilter

"blog_20141127_20_2124714" name="code" >
AcceptOnMatch (false)
LogLevelMin
LogLevelMax

3.3.4 StringMatchFilter

"blog_20141127_21_8145354" name="code" >
AcceptOnMatch (false)
StringToMatch
3.4 loggers配置(log4cplus.)

3.4.1 log4cplus全局配置

"blog_20141127_22_7504440" name="code" >
configDebug (false)
quietMode (false)
disableOverride (false)

3.4.2 logger配置及父子关系

"blog_20141127_22_7504440" name="code" >
rootLogger
logger.
additivity.
INHERITED
3.5 配置文件包涵关系 include

4.1 方法说明及示例
Read configuration from a file. The existing configuration is not cleared nor reset. If you require a different behavior, then call {@link Hierarchy::resetConfiguration resetConfiguration} method before callingdoConfigure.

The configuration file consists of statements in the format key=value. The syntax of different configuration elements are discussed below.

Appender configuration
Appender configuration syntax is:
"blog_20141127_16_4005594" name="code" >
# For appender named <em>appenderName</em>, set its class.
# Note: The appender name can contain dots.
log4cplus.appender.appenderName=fully.qualified.name.of.appender.class
# Set appender specific options.
log4cplus.appender.appenderName.option1=value1
...
log4cplus.appender.appenderName.optionN=valueN
For each named appender you can configure its {@link Layout}. The syntax for configuring an appender's layout is: log4cplus.appender.appenderName.layout=fully.qualified.name.of.layout.class
log4cplus.appender.appenderName.layout.option1=value1
....
log4cplus.appender.appenderName.layout.optionN=valueN
Configuring loggers The syntax for configuring the root logger is: log4cplus.rootLogger=[LogLevel], appenderName, appenderName, ...
This syntax means that an optionalLogLevel value can be supplied followed by appender names separated by commas.

The LogLevel value can consist of the string values FATAL, ERROR, WARN, INFO, DEBUG or acustom LogLevel value.

If a LogLevel value is specified, then the root LogLevel is set to the corresponding LogLevel. If no LogLevel value is specified, then the root LogLevel remains untouched.

The root logger can be assigned multiple appenders.

Each appenderName (separated by commas) will be added to the root logger. The named appender is defined using the appender syntax defined above.

For non-root loggers the syntax is almost the same:

log4cplus.logger.logger_name=[LogLevel|INHERITED], appenderName, appenderName, ...
The meaning of the optional LogLevel value is discussed above in relation to the root logger. In addition however, the value INHERITED can be specified meaning that the named logger should inherit its LogLevel from the logger hierarchy.

By default loggers inherit their LogLevel from the hierarchy. However, if you set the LogLevel of a logger and later decide that that logger should inherit its LogLevel, then you should specify INHERITED as the value for the LogLevel value.

Similar to the root logger syntax, each appenderName (separated by commas) will be attached to the named logger.

See the appender additivity rule in the user manual for the meaning of theadditivity flag.

The user can override any of the {@link Hierarchy#disable} family of methods by setting the a key "log4cplus.disableOverride" totrue or any value other than false. As in

log4cplus.disableOverride=true
Example An example configuration is given below. # Set options for appender named "A1".
# Appender "A1" will be a SyslogAppender
log4cplus.appender.A1=log4cplus::SyslogAppender
# The syslog daemon resides on
log4cplus.appender.A1.SyslogHost=
# A1's layout is a PatternLayout, using the conversion pattern
# <strong>%r %-5p %c{2} %M.%L %x - %m\n</strong>. Thus, the log output will
# include # the relative time since the start of the application in
# milliseconds, followed by the LogLevel of the log request,
# followed by the two rightmost components of the logger name,
# followed by the callers method name, followed by the line number,
# the nested disgnostic context and finally the message itself.
# Refer to the documentation of {@link PatternLayout} for further information
# on the syntax of the ConversionPattern key.
log4cplus.appender.A1.layout=log4cplus::PatternLayout
log4cplus.appender.A1.layout.ConversionPattern=%-4r %-5p %c{2} %M.%L %x - %m\n
# Set options for appender named "A2"
# A2 should be a RollingFileAppender, with maximum file size of 10 MB
# using at most one backup file. A2's layout is TTCC, using the
# ISO8061 date format with context printing enabled.
log4cplus.appender.A2=log4cplus::RollingFileAppender
log4cplus.appender.A2.MaxFileSize=10MB
log4cplus.appender.A2.MaxBackupIndex=1
log4cplus.appender.A2.layout=log4cplus::TTCCLayout
log4cplus.appender.A2.layout.ContextPrinting=true
log4cplus.appender.A2.layout.DateFormat=ISO8601
# Root logger set to DEBUG using the A2 appender defined above.
log4cplus.rootLogger=DEBUG, A2
# Logger definitions:
# The SECURITY logger inherits is LogLevel from root. However, it's output
# will go to A1 appender defined above. It's additivity is non-cumulative.
log4cplus.logger.SECURITY=INHERIT, A1
log4cplus.additivity.SECURITY=false
# Only warnings or above will be logged for the logger "SECURITY.access".
# Output will go to A1.
log4cplus.logger.SECURITY.access=WARN
# The logger "class.of.the.day" inherits its LogLevel from the
# logger hierarchy. Output will go to the appender's of the root
# logger, A2 in this case.
log4cplus.logger.class.of.the.day=INHERIT
Refer to the setOption method in each Appender and Layout for class specific options.

Use the # character at the beginning of a line for comments.

4.2 配置文件示例
log4cplus.properties文件

"blog_20141128_33_4542586" name="code" >
log4cplus.rootLogger=INFO, STDOUT, R
log4cplus.logger.test.a.b.c=WARN
log4cplus.logger.filelogger=WARN, R, TEST
log4cplus.additivity.filelogger=FALSE
log4cplus.appender.STDOUT=log4cplus::ConsoleAppender
log4cplus.appender.STDOUT.layout=log4cplus::PatternLayout
log4cplus.appender.STDOUT.layout.ConversionPattern=%d{%m/%d/%y %H:%M:%S} [%t] %-5p %c{2} %%%x%% - %m [%l]%n
include log4cplus.tail.properties
log4cplus.tail.properties文件 log4cplus.appender.R=log4cplus::RollingFileAppender
log4cplus.appender.R.File=output_${ENV_VAR}.log
#log4cplus.appender.R.MaxFileSize=5MB
log4cplus.appender.R.MaxFileSize=500KB
log4cplus.appender.R.MaxBackupIndex=5
log4cplus.appender.R.layout=log4cplus::TTCCLayout
#log4cplus.appender.TEST=log4cplus::NullAppender
log4cplus.appender.TEST=log4cplus::FileAppender
log4cplus.appender.TEST.File=test_output.log
# For AsyncAppender testing.
#log4cplus.appender.TEST=log4cplus::AsyncAppender
#log4cplus.appender.TEST.Appender=log4cplus::FileAppender
#log4cplus.appender.TEST.Appender.File=test_output.log
#log4cplus.appender.TEST.Appender.layout=log4cplus::PatternLayout
#log4cplus.appender.TEST.Appender.layout.ConversionPattern=%d{%y-%m-%d %H:%M:%S,%q} [%t] %-5p %c <%x> - %m%n
#log4cplus.appender.TEST.layout=log4cplus::TTCCLayout
log4cplus.appender.TEST.layout=log4cplus::PatternLayout
log4cplus.appender.TEST.layout.ConversionPattern=%d{%y-%m-%d %H:%M:%S,%q} [%t] %-5p %c <%x> - %m%n
#log4cplus.appender.TEST.layout.ConversionPattern=%d{%y-%m-%d %H:%M:%S,%q} %-5p %c <%x> - %m%n
#log4cplus.appender.TEST.layout.ConversionPattern=%p - %m%n
#log4cplus.appender.TEST.layout.ConversionPattern=%-5p - %m%n
#log4cplus.appender.TEST.layout.ConversionPattern=%l - %m%n
#log4cplus.appender.TEST.layout.ConversionPattern=%C.%M.%L - %m%n
#log4cplus.appender.TEST.layout.ConversionPattern=%D{%Y/%m/%d %H:%M:%S,%Q} %r [%t] %-5p %c{2} <%x> - %m [%l:%M]%n

cruise_log4cplus_init_single.h

"blog_20141216_37_9900272" name="code" >
#pragma once
//#include "cruise_config.h"
//#define CRUISE_LOG4CPLUS
#ifdef CRUISE_LOG4CPLUS
#include <log4cplus/logger.h>
#include <log4cplus/helpers/snprintf.h>
#include <log4cplus/configurator.h>
#include <log4cplus/loggingmacros.h>
//#define LOG4CPLUS_STATIC
#ifdef LOG4CPLUS_STATIC
//#pragma comment(lib, "advapi32") // NTEventLogAppender
#define CRUISE_LOG4CPLUS
#endif
static log4cplus::Logger& get_logger()
{
static log4cplus::Logger logger;
return logger;
}
#define g_Logger get_logger()
static inline log4cplus::tstring file_name_add_prefix(log4cplus::tstring& old_name,
log4cplus::tstring prefix_flie);
static inline void change_log_file_name(log4cplus::tchar* prop_file,
log4cplus::tchar* prefix_log_flie);
static inline void log_init_log4cplus(log4cplus::tchar* prop_file,
log4cplus::tchar* prefix_log_flie = NULL,
log4cplus::tchar* sub_logger_name = NULL)
{
log4cplus::initialize();
g_Logger = log4cplus::Logger::getRoot();
if (NULL == prop_file) return;
try
{
if (NULL != prefix_log_flie && '\0' != prefix_log_flie[0])
change_log_file_name(prop_file, prefix_log_flie);
else
log4cplus::PropertyConfigurator::doConfigure(prop_file);
//log4cplus::ConfigureAndWatchThread cfg_thread(prop_file, 24*60*60*1000);
if (NULL != sub_logger_name && '\0' != sub_logger_name[0]
&& log4cplus::Logger::exists(sub_logger_name))
g_Logger = log4cplus::Logger::getInstance(sub_logger_name);
//else
// g_Logger = log4cplus::Logger::getRoot();
LOG4CPLUS_INFO(g_Logger, LOG4CPLUS_TEXT("Log System Start."));
}
catch (...)
{
LOG4CPLUS_FATAL(g_Logger, LOG4CPLUS_TEXT("Exception occured..."));
abort();
}
}
static inline void log_uinit_log4cplus()
{
LOG4CPLUS_INFO(g_Logger, LOG4CPLUS_TEXT("Log System Stop."));
log4cplus::Logger::shutdown();
}
static inline void change_log_file_name(log4cplus::tchar* prop_file,
log4cplus::tchar* prefix_log_flie)
{
log4cplus::PropertyConfigurator prop_config(prop_file);
log4cplus::helpers::Properties& prop
= const_cast<log4cplus::helpers::Properties &>(
prop_config.getProperties());
log4cplus::helpers::Properties appender_properties
= prop.getPropertySubset(LOG4CPLUS_TEXT("appender."));
std::vector<log4cplus::tstring> appenders_props
= appender_properties.propertyNames();
for (std::vector<log4cplus::tstring>::iterator
it = appenders_props.begin(); it != appenders_props.end(); ++it)
{
if (log4cplus::tstring::npos != it->find(
LOG4CPLUS_TEXT(".File")))
{
log4cplus::tstring file_name_old
= appender_properties.getProperty(*it);
log4cplus::tstring file_name_new
= file_name_add_prefix(file_name_old, prefix_log_flie);
prop.setProperty(LOG4CPLUS_TEXT("appender.") + *it, file_name_new);
}
}
prop_config.configure();
}
static inline log4cplus::tstring file_name_add_prefix(log4cplus::tstring& old_name,
log4cplus::tstring prefix_flie)
{
size_t pos = 0;
if (log4cplus::tstring::npos != (
pos = old_name.find_last_of(LOG4CPLUS_TEXT('\\')))
|| log4cplus::tstring::npos != (
pos = old_name.find_last_of(LOG4CPLUS_TEXT('/'))))
{
++pos;
}
prefix_flie.append(LOG4CPLUS_TEXT("_"));
return old_name.insert(pos, prefix_flie);
}
/************************************************************************/
/* Log out macro */
/************************************************************************/
//#define LOGGER_ROOT log4cplus::Logger::getRoot()
#define LOG_ASSERT(cond) LOG4CPLUS_ASSERT(g_Logger, cond)
#define LOG_METHOD(logEvent) LOG4CPLUS_TRACE_METHOD(g_Logger, logEvent)
#define LOG_FATAL(logEvent) LOG4CPLUS_FATAL(g_Logger, logEvent)
#define LOG_ERROR(logEvent) LOG4CPLUS_ERROR(g_Logger, logEvent)
#define LOG_WARN(logEvent) LOG4CPLUS_WARN(g_Logger, logEvent)
#define LOG_INFO(logEvent) LOG4CPLUS_INFO(g_Logger, logEvent)
#define LOG_DEBUG(logEvent) LOG4CPLUS_DEBUG(g_Logger, logEvent)
#define LOG_TRACE(logEvent) LOG4CPLUS_TRACE(g_Logger, logEvent)
#if _MSC_VER > 1400
#define LOG_FATAL_FMT(logFmt, ...) LOG4CPLUS_FATAL_FMT(g_Logger, logFmt, __VA_ARGS__)
#define LOG_ERROR_FMT(logFmt, ...) LOG4CPLUS_ERROR_FMT(g_Logger, logFmt, __VA_ARGS__)
#define LOG_WARN_FMT(logFmt, ...) LOG4CPLUS_WARN_FMT(g_Logger, logFmt, __VA_ARGS__)
#define LOG_INFO_FMT(logFmt, ...) LOG4CPLUS_INFO_FMT(g_Logger, logFmt, __VA_ARGS__)
#define LOG_DEBUG_FMT(logFmt, ...) LOG4CPLUS_DEBUG_FMT(g_Logger, logFmt, __VA_ARGS__)
#define LOG_TRACE_FMT(logFmt, ...) LOG4CPLUS_TRACE_FMT(g_Logger, logFmt, __VA_ARGS__)
#endif
/************************************************************************/
/* MACRO: _T, _TEXT, TEXT */
/* TYPE: tchar , tstring */
/************************************************************************/
#ifndef _T
#define _T(x) LOG4CPLUS_TEXT(x)
#endif
#ifndef _TEXT
#define _TEXT(x) _T(x)
#endif
#ifndef TEXT
#define TEXT(x) _T(x)
#endif
using log4cplus::tchar;
using log4cplus::tstring;
using log4cplus::tistream;
using log4cplus::tostream;
using log4cplus::tcout;
using log4cplus::tcerr;
#define CRUISE_C_STR_TO_TSTRING(STRING) LOG4CPLUS_C_STR_TO_TSTRING(STRING)
#define CRUISE_STRING_TO_TSTRING(STRING) LOG4CPLUS_STRING_TO_TSTRING(STRING)
#define CRUISE_TSTRING_TO_STRING(STRING) LOG4CPLUS_TSTRING_TO_STRING(STRING)
#define CRUISE_BUILTIN_EXPECT(exp, c) LOG4CPLUS_BUILTIN_EXPECT(exp, c)
#define CRUISE_LIKELY(cond) LOG4CPLUS_LIKELY(cond)
#define CRUISE_UNLIKELY(cond) LOG4CPLUS_UNLIKELY(cond)
//#define CRUISE_MACRO_FILE() __FILE__
//#define CRUISE_MACRO_LINE() __LINE__
#define CRUISE_MACRO_FUNCTION() LOG4CPLUS_MACRO_FUNCTION()
#define CRUISE_CALLER_FILE() LOG4CPLUS_CALLER_FILE()
#define CRUISE_CALLER_LINE() LOG4CPLUS_CALLER_LINE()
#define CRUISE_CALLER_FUNCTION() LOG4CPLUS_CALLER_FUNCTION()
#else // !CRUISE_LOG4CPLUS
#include <cstdio> // printf
#include <cstdlib>
#include <iostream> // std::cout, std::cerr, std::endl
#pragma warning(disable:4996)
/************************************************************************/
/* MACRO: _T, _TEXT, TEXT */
/* TYPE: tchar , tstring */
/************************************************************************/
#ifndef _T
#if UNICODE
#define _T(x) L ## x
#else
#define _T(x) x
#endif
#endif
#ifndef _TEXT
#define _TEXT(x) _T(x)
#endif
#ifndef TEXT
#define TEXT(x) _T(x)
#endif
#if UNICODE
typedef wchar_t tchar;
typedef std::wstring tstring;
typedef std::wistream tistream;
typedef std::wostream tostream;
//static tostream& tcout = std::wcout;
//static tostream& tcerr = std::wcerr;
#define tprintf wprintf
#else
typedef char tchar;
typedef std::string tstring;
typedef std::istream tistream;
typedef std::ostream tostream;
//static tostream& tcout = std::cout;
//static tostream& tcerr = std::cerr;
#define tprintf printf
#endif
//typedef std::basic_string<tchar, std::char_traits<tchar>, std::allocator<tchar>> tstring;
//typedef std::basic_ostream<tchar, std::char_traits<tchar> > tostream;
//typedef std::basic_istream<tchar, std::char_traits<tchar> > tistream;
static tostream& get_tcout()
{
#if UNICODE
static tostream& s_tcout = std::wcout;
#else
static tostream& s_tcout = std::cout;
#endif
return s_tcout;
}
#define tcout get_tcout()
static tostream& get_tcerr()
{
#if UNICODE
static tostream& s_tcerr = std::wcerr;
#else
static tostream& s_tcerr = std::cerr;
#endif
return s_tcerr;
}
#define tcerr get_tcerr()
static std::string ws2s(const std::wstring& ws)
{
std::string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C";
setlocale(LC_ALL, "");
const wchar_t* _Source = ws.c_str();
size_t _Dsize = 2 * ws.size() + 1;
char *_Dest = new char[_Dsize];
memset(_Dest, 0, _Dsize);
wcstombs(_Dest, _Source, _Dsize);
std::string result = _Dest;
delete[]_Dest;
setlocale(LC_ALL, curLocale.c_str());
return result;
}
static std::wstring s2ws(const std::string& s)
{
setlocale(LC_ALL, "");
const char* _Source = s.c_str();
size_t _Dsize = s.size() + 1;
wchar_t *_Dest = new wchar_t[_Dsize];
wmemset(_Dest, 0, _Dsize);
mbstowcs(_Dest, _Source, _Dsize);
std::wstring result = _Dest;
delete[]_Dest;
setlocale(LC_ALL, "C");
return result;
}
static tstring ws2t(const std::wstring ws)
{
#if UNICODE
return ws;
#else
return ws2s(ws);
#endif
}
static tstring s2t(const std::string s)
{
#if UNICODE
return s2ws(s);
#else
return s;
#endif
}
static std::string t2s(const tstring s)
{
#if UNICODE
return ws2s(s);
#else
return s;
#endif
}
#define CRUISE_C_STR_TO_TSTRING(STRING) s2t(STRING)
#define CRUISE_STRING_TO_TSTRING(STRING) s2t(STRING)
#define CRUISE_TSTRING_TO_STRING(STRING) t2s(STRING)
/************************************************************************/
/* CRUISE_MACRO_FUNCTION() */
/* __FILE__, __LINE__ */
/************************************************************************/
//#define CRUISE_MACRO_FILE() __FILE__
//#define CRUISE_MACRO_LINE() __LINE__
#define CRUISE_MACRO_FUNCTION() 0
#if defined(_MSC_VER) && _MSC_VER > 1400
# undef CRUISE_MACRO_FUNCTION
# define CRUISE_MACRO_FUNCTION() __FUNCSIG__
#elif defined(__GNUC__) \
&& __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)
# undef CRUISE_MACRO_FUNCTION
# define CRUISE_MACRO_FUNCTION() __PRETTY_FUNCTION__
#elif defined(__BORLANDC__) && __BORLANDC__ >= 0x0650
# undef CRUISE_MACRO_FUNCTION
# define CRUISE_MACRO_FUNCTION() __FUNCTION__
//# define CRUISE_MACRO_FUNCTION() __FUNC__ //C++ BuilderX
#elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 19901L) \
|| (defined(__GNUC__) && __GNUC__ > 3 \
|| (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
# undef CRUISE_MACRO_FUNCTION
# define CRUISE_MACRO_FUNCTION() __func__
#endif
#if defined (__GNUC__) \
&& (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
# define CRUISE_CALLER_FILE() __builtin_FILE ()
# define CRUISE_CALLER_LINE() __builtin_LINE ()
# define CRUISE_CALLER_FUNCTION() __builtin_FUNCTION ()
#else
# define CRUISE_CALLER_FILE() (NULL)
# define CRUISE_CALLER_LINE() (-1)
# define CRUISE_CALLER_FUNCTION() (NULL)
#endif
class cruise_trace_logger
{
public:
cruise_trace_logger(const tstring& _msg,
const char* _file = CRUISE_CALLER_FILE(),
int _line = CRUISE_CALLER_LINE(),
char const * _function = CRUISE_CALLER_FUNCTION())
: msg(_msg), file(_file), function(_function), line(_line)
{
tcout << "ENTER: " << msg.c_str()
<< " [" << file << ":" << line << ":" << function << "]"
<< std::endl;
}
~cruise_trace_logger()
{
tcout << "EXIT: " << msg.c_str()
<< " [" << file << ":" << line << ":" << function << "]"
<< std::endl;
}
private:
cruise_trace_logger(cruise_trace_logger const &);
cruise_trace_logger & operator = (cruise_trace_logger const &);
tstring msg;
const char* file;
const char* function;
int line;
};
/************************************************************************/
/* Log out macro */
/************************************************************************/
#define LOG_METHOD(logEvent) \
cruise_trace_logger _trace_logger(logEvent, \
__FILE__, __LINE__, CRUISE_MACRO_FUNCTION())
#define CRUISE_DEBUG_COUT(logEvent) \
tcout << logEvent << " [" \
<< __FILE__ << ":" << __LINE__<< ":" \
<< CRUISE_MACRO_FUNCTION() << "]" << std::endl
#define CRUISE_DEBUG_CERR(logEvent) \
tcerr << logEvent << " [" \
<< __FILE__ << ":" << __LINE__<< ":" \
<< CRUISE_MACRO_FUNCTION() << "]" << std::endl
#define LOG_FATAL(logEvent) CRUISE_DEBUG_CERR(logEvent)
#define LOG_ERROR(logEvent) CRUISE_DEBUG_CERR(logEvent)
#define LOG_WARN(logEvent) CRUISE_DEBUG_COUT(logEvent)
#define LOG_INFO(logEvent) CRUISE_DEBUG_COUT(logEvent)
#define LOG_DEBUG(logEvent) CRUISE_DEBUG_COUT(logEvent)
#define LOG_TRACE(logEvent) CRUISE_DEBUG_COUT(logEvent)
#if _MSC_VER > 1400
#define CRUISE_DEBUG_PRINTF(logFmt, ...) \
tprintf(logFmt, __VA_ARGS__); \
tprintf(_T(" [%s:%d:%s]\n"), \
CRUISE_C_STR_TO_TSTRING(__FILE__).c_str(), __LINE__, \
CRUISE_C_STR_TO_TSTRING(CRUISE_MACRO_FUNCTION()).c_str());
#define LOG_FATAL_FMT(logFmt, ...) CRUISE_DEBUG_PRINTF(logFmt, __VA_ARGS__)
#define LOG_ERROR_FMT(logFmt, ...) CRUISE_DEBUG_PRINTF(logFmt, __VA_ARGS__)
#define LOG_WARN_FMT(logFmt, ...) CRUISE_DEBUG_PRINTF(logFmt, __VA_ARGS__)
#define LOG_INFO_FMT(logFmt, ...) CRUISE_DEBUG_PRINTF(logFmt, __VA_ARGS__)
#define LOG_DEBUG_FMT(logFmt, ...) CRUISE_DEBUG_PRINTF(logFmt, __VA_ARGS__)
#define LOG_TRACE_FMT(logFmt, ...) CRUISE_DEBUG_PRINTF(logFmt, __VA_ARGS__)
#endif
#if defined (__GNUC__) && __GNUC__ >= 3
# define CRUISE_BUILTIN_EXPECT(exp, c) __builtin_expect ((exp), (c))
#else
# define CRUISE_BUILTIN_EXPECT(exp, c) (exp)
#endif
#define CRUISE_LIKELY(cond) CRUISE_BUILTIN_EXPECT(!! (cond), 1)
#define CRUISE_UNLIKELY(cond) CRUISE_BUILTIN_EXPECT(!! (cond), 0)
#define LOG_ASSERT(cond) \
if (CRUISE_UNLIKELY(!cond)) \
LOG_FATAL("failed condition: "#cond);
#endif
static void cruise_set_loc()
{
#if (defined(__linux__) || defined(__linux) \
|| defined(linux) || defined(__gnu_linux__)) \
&& defined(__GNUC_)
std::ios::sync_with_stdio(false); // Linux gcc.
#endif
std::locale::global(std::locale(""));
#if defined(__MINGW32__) // Windows32 by mingw compiler
setlocale(LC_CTYPE, ""); // MinGW gcc.
#endif
tcout.imbue(std::locale(""));
}
static void log_init(tchar* prop_file,
tchar* prefix_log_flie = NULL, tchar* sub_logger_name = NULL)
{
#ifdef CRUISE_LOG4CPLUS
log_init_log4cplus(prop_file, prefix_log_flie, sub_logger_name);
#else
cruise_set_loc();
#endif
}
static void log_uinit()
{
#ifdef CRUISE_LOG4CPLUS
log_uinit_log4cplus();
#endif
}

log4cplus 使用方法 配置 - wclhjs的个人空间
日志信息的编写与调用 - 笑笑小白
对 log4cplus 的一个实现 - 笑笑小白
开源日志系统log4cplus - 笑笑小白
Log4cplus日志系统和产一Willow基础库日志模块源代码分析
Log4cplus使用指南 - keep_simple