Log4j2日志配置详解

and different log4j log4j: log4j Logger object is acquired by the static method of the getLogger Logger (), and log4j2 Logger object is acquired by the static method getLogger LogManager ().

Detailed 1.log4j2

1. log4j2 principle

class log4j classes

  Use log4j 2 api application LogManager request from the recorder with a specific name. LogManager will find the appropriate LoggerContext, and then derive recorder. If the recorder must be created, it is associated with LoggerConfig, loggerconfig comprising a) the name of the same recorder, b) the name of the parent package, or c) a root LoggerConfig. LoggerConfig object is created from the recorder statement configuration. LoggerConfig the actual transfer logevents appender associated.

2.logger hierarchy

  Compared with ordinary system.out.println, the primary advantage of any logging api lies in its ability to disable certain log statements while allowing others to print unhindered. This function assumes that log space (ie the space of all possible logging statements) are classified according to certain conditions chosen by the developer. In log4j 1.x, recording hierarchy is the relationship between the recorders to maintain. In log4j 2, this relationship no longer exists. On the contrary, the hierarchy is maintained in the relationship between loggerconfig object .

loggers and loggerconfigs is named entities. Logger names are case sensitive, and follow the hierarchical naming rule:

Nameed HierchaHierarchy
A LoggerConfig is said to be an ancestor of another LoggerConfig if its name followed by a dot is a prefix of the descendant logger name.
A LoggerConfig is said to be a parent of a child LoggerConfig if there are no ancestors between itself and the descendant LoggerConfig.

For example, the LoggerConfig named "com.foo" is a parent of the LoggerConfig named"com.foo.Bar".

Root LoggerConfig LoggerConfig at the top of the hierarchy. It is an exception, because it is always there, it is part of every level. Direct link to the root LoggerConfig recorder can be obtained as follows:

Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

There's an easier way to get way:

Logger logger = LogManager.getRootLogger ();

For all other types of recording device, can be obtained by the static method getLogger the LogManager. Please refer to the specific use log4j2 API.

3.LoggerContext

loggercontext act as an anchor point logging system. However, under specific circumstances, the application may have multiple activities loggercontext. For more details on loggercontext, see separate log section.

4.Configuration

Each loggercontext has an active configuration. Configuration contains all the appender, Filters context range, loggerconfigs and a reference to the strsubstitutor. During the reconfiguration, there will be two configuration objects. Once all of the records is redirected to the new configuration, the old configuration will be stopped and discarded.

5.Logger

As mentioned earlier, create a record by calling logmanager.getlogger. The recorder itself does not perform any direct operations. It just has a name, and is associated with loggerconfig. It extends AbstractLogger and implement methods required. When the configuration is modified, the recorder may be associated with a different loggerconfig, causing its behavior is modified.

For example: x and y references point to the same exact Logger object.

Logger x = LogManager.getLogger("wombat");
Logger y = LogManager.getLogger("wombat");

Configure log4j environment is typically done at application initialization. The preferred method is to read the configuration file.

log4j by the software component named logger easy. This can be achieved in each class instantiates the recorder, the recorder name equals fully qualified class name. This is a useful definition of the recorder and direct method. Since the log output log generated with the name, so that this naming strategy to identify the source of the log message easily. However, this is only one possible (although very common) strategy logger named. log4j not limited set of possible recorder. Developers can name the recorder under the Freedom of need. Since class has named logger is a common idiom, thus providing a convenient method LogManager.getLogger () to automatically use the fully qualified name of the class call the class as a logger name. However, with the class where the logger name logger seems to be the best strategy currently known.

6.LoggerConfig

loggerconfig object is created when you declare a logger in the log configuration. loggerconfig contains a set of filters, these filters must be passed prior to allowing logevent passed to any additional procedures. It contains additional procedures used in handling events of reference set.

6.1 log levels

loggerConfigs will be assigned a log level. Built-level set includes trace, debug, info, warn, error, and fatal. log4j 2 also supports custom log level. Another mechanism is to use more size markers.

log4j 1.x and logback have a " level of inheritance " concept. In the log4j 2, and loggerconfigs Loggers are two different objects, the different implementations of this concept. Each logger reference the appropriate loggerconfig.

7.Filter

After addition to the automatic log-level filtering as carried out in the previous section, log4j also be provided in the control passed to any LoggerConfig before control is passed to LoggerConfig, the appender before any call, control is passed to the filter after application l. But before calling a particular appender, and on each appender. In a very similar manner to the firewall filters, each filter may return one of three results, accepted, rejected, or neutral. The response indicates that the call should not accept other filters, the event should continue. Refused to respond immediately should mean to ignore the event, and returns control to the caller. Neutral response indicates that the event should be passed to other filters. If there are no other filters, the event will be handled.

While filters can accept the event, but still could not record the event. When the event is the pre-loggerconfig filters to accept, but was subsequently rejected or loggerconfig filters reject all additional programs, this situation may occur.

8.appender

  The ability to enable or disable logging requests based on selective logging program is only part of the picture. log4j allows logging requests to print to multiple destinations. In log4j speak, the output destination called appender. Currently, console, file, remote socket servers, apache flume, jms, remote unix syslog daemon and various databases api have additional procedures. For more information about the various types available, see appendix. A plurality of recording additional programs may be connected.

  Can be added to the recording method by calling addLoggerAppender additional program current configuration. If loggerconfig recorder matches the name does not exist, create a loggerconfig, additional programs will be attached to it, and then inform all record updates its loggerconfig reference.

  All additional program and an additional program loggerconfig parent loggerconfig recording request is given to each log records are forwarded to enable the recorder to the . In other words, appender is an additional inherited from loggerconfig hierarchy. For example, if the additional program is added to the root console logger, then all enabled logging requests to print at least on the console. If you add an additional file in loggerconfig (such as c), the log records so children of c and c-enabled file and print requests to the console. You can override this default behavior to set additivity = "false" by the recorder or in the configuration file, no longer appender accumulation.

Rules on appender additivity are summarized below.

8.log4j 1.x Migration

1.Using the Log4j 1.x bridge

Perhaps the simplest is converted to use log4j 2 is to replace the log4j 1.xjar file log4j2 log4j-1.2-api.jar. However, to successfully use this application, you must meet the following requirements:

1. log4j 1.x they can not access the interior of the methods and classes implemented as callAppenders method Appenders, LoggerRepository or the Category.

2. They can not programmatically configure log4j.

3. They can not, or by calling class DomConfigurator PropertyConfigurator configuration.

2.Converting to the Log4j 2 API

In most cases, from log4j 1.x api to convert log4j 2 should be fairly simple. Many log statements do not need to be modified. However, if necessary, must make the following changes:

1 1. The main package version is org.apache.log4j, the main package version 2 is org.apache.logging.log4j

2. Call for org.apache.log4j.Logger.getLogger () must be modified to org.apache.logging.log4j.LogManager.getLogger ().

3. Call for org.apache.log4j.Logger.getRootLogger () or org.apache.log4j.LogManager.getRootLogger () must be replaced org.apache.logging.log4j.LogManager.getRootLogger ().

4. Call org.apache.log4j.Logger.getLogger accepted LoggerFactory must remove org.apache.log4j.spi.LoggerFactory and use one of the other extension mechanism log4j 2.

5. replace the call will org.apache.log4j.Logger.getEffectiveLevel () is org.apache.logging.log4j.Logger.getLevel ().

6. Remove the call to org.apache.log4j.LogManager.shutdown (), and do not need them in version 2, because the core log4j now automatically adds a jvm shutdown hooks to perform any cleanup core at startup.

  Starting log4j 2.1, you can specify a custom shutdownCallbackRegistry to override the default jvm shutdown hook strategies.

  From log4j 2.6, you can now use org.apache.logging.log4j.LogManager.shutdown () to manually start off.

7.API call to org.apache.log4j.Logger.setLevel () or similar methods are not supported. The application should remove them. log4j 2 implementation class provides the equivalent functionality, see org.apache.logging.log4j.core.config.Configurator.setLevel (), but can make the application vulnerable to internal log4j2 change.

8. where appropriate, should be converted to the application of the message parameter, not the string concatenation.

9.org.apache.log4j.MDC and org.apache.log4j.NDC have been replaced thread context.

3.configuring Log4j2

Although log4j 2 configuration syntax is different log4j 1.x, but most (if not all) of the same functionality is available.

Note that, by $ {foo} syntax interpolation system properties have been extended to allow for Find property from many different sources. For more information, see Finding documentation. For example, in the system property named log4j 1.x catalina.base lookup syntax will be $ {catalina.base}. In log4j 2, the syntax is $ {sys: catalina.base}.

log4j 1.x with a different log4j xmlayout in 2 xmlayout, log4j-1.2-api module contains a log4j1xmlayout, it generates the output log4j 1.x format. log4j 1.x simplelayout can be simulated with patternlayout% level-% m% n. log4j 1.x ttcclayout can patternlayout "% r [% t]% p% c% notempty {% ndc} -% m% n" analog.

The log4j 1.x patternLayout enhancedPatternLayout and can be replaced as the log4j 2 patternLayout. log4j-1.2-api mode switching module contains two "% ndc" and "% properties", can be used to simulate the log4j 1.x patternlayout "% x" and "% x" in (log4j 2% x% x and the format is slightly different).

 

The following is a configuration example in log4j 1.x and corresponding log4j 2:

Sample 1 - Simple configuration using a Console Appender

Log4j 1.x XML configuration

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
  <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
    </layout>
  </appender>
  <category name="org.apache.log4j.xml">
    <priority value="info" />
  </category>
  <Root>
    <priority value ="debug" />
    <appender-ref ref="STDOUT" />
  </Root>
</log4j:configuration>

Log4j 2 XML configuration

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Logger name="org.apache.log4j.xml" level="info"/>
    <Root level="debug">
      <AppenderRef ref="STDOUT"/>
    </Root>
  </Loggers>
</Configuration>

Sample 2 - Simple configuration using a File Appender, XMLLayout and SimpleLayout

Log4j 1.x XML configuration

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <appender name="A1" class="org.apache.log4j.FileAppender">
    <param name="File"   value="A1.log" />
    <param name="Append" value="false" />
    <layout class="org.apache.log4j.xml.XMLLayout" />
  </appender>
  <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.SimpleLayout" />
  </appender>
  <category name="org.apache.log4j.xml">
    <priority value="debug" />
    <appender-ref ref="A1" />
  </category>
  <root>
    <priority value ="debug" />
    <appender-ref ref="STDOUT" />
  </Root>
</log4j:configuration>

Log4j 2 XML configuration

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <File name="A1" fileName="A1.log" append="false">
      <Log4j1XmlLayout />
    </File>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%level - %m%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Logger name="org.apache.log4j.xml" level="debug">
      <AppenderRef ref="A1"/>
    </Logger>
    <Root level="debug">
      <AppenderRef ref="STDOUT"/>
    </Root>
  </Loggers>
</Configuration>

Sample 3 - SocketAppender

Log4j 1.x XML configuration. This example from Log4j 1.x is misleading. The SocketAppender does not actually use a Layout. Configuring one will have no effect.

 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <appender name="A1" class="org.apache.log4j.net.SocketAppender">
    <param name="RemoteHost" value="localhost"/>
    <param name="Port" value="5000"/>
    <param name="LocationInfo" value="true"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%t %-5p %c{2} - %m%n"/>
    </layout>
  </appender>
  <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
    </layout>
  </appender>
  <category name="org.apache.log4j.xml">
    <priority value="debug"/>
    <appender-ref ref="A1"/>
  </category>
  <root>
    <priority value="debug"/>
    <appender-ref ref="STDOUT"/>
  </Root>
</log4j:configuration>

Log4j 2 XML configuration

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <Socket name="A1" host="localHost" port="5000">
      <PatternLayout pattern="%t %-5p %c{2} - %m%n"/>
    </Socket>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Logger name="org.apache.log4j.xml" level="debug">
      <AppenderRef ref="A1"/>
    </Logger>
    <Root level="debug">
      <AppenderRef ref="STDOUT"/>
    </Root>
  </Loggers>
</Configuration>

Sample 4 - AsyncAppender and TTCCLayout

Log4j 1.x XML configuration using the AsyncAppender.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" configDebug="true">
  <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
    <appender-ref ref="TEMP"/>
  </appender>
  <appender name="TEMP" class="org.apache.log4j.FileAppender">
    <param name="File" value="temp"/>
    <layout class="org.apache.log4j.TTCCLayout">
      <param name="ThreadPrinting" value="true"/>
      <param name="CategoryPrefixing" value="true"/>
      <param name="ContextPrinting" value="true"/>
    </layout>
  </appender>
  <root>
    <priority value="debug"/>
    <appender-ref ref="ASYNC"/>
  </Root>
</log4j:configuration>

Log4j 2 XML configuration.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
  <Appenders>
    <File name="TEMP" fileName="temp">
      <PatternLayout pattern="%r [%t] %p %c %notEmpty{%ndc }- %m%n"/>
    </File>
    <Async name="ASYNC">
      <AppenderRef ref="TEMP"/>
    </Async>
  </Appenders>
  <Loggers>
    <Root level="debug">
      <AppenderRef ref="ASYNC"/>
    </Root>
  </Loggers>
</Configuration>

Sample 5 - AsyncAppender with Console and File

Log4j 1.x XML configuration using the AsyncAppender.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" configDebug="true">
  <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
    <appender-ref ref="TEMP"/>
    <appender-ref ref="CONSOLE"/>
  </appender>
  <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
    </layout>
  </appender>
  <appender name="TEMP" class="org.apache.log4j.FileAppender">
    <param name="File" value="temp"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
    </layout>
  </appender>
  <root>
    <priority value="debug"/>
    <appender-ref ref="ASYNC"/>
  </Root>
</log4j:configuration>

Log4j 2 XML configuration. Note that the Async Appender should be configured after the appenders it references. This will allow it to shutdown properly.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
  <Appenders>
    <Console name="CONSOLE" target="SYSTEM_OUT">
      <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
    </Console>
    <File name="TEMP" fileName="temp">
      <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
    </File>
    <Async name="ASYNC">
      <AppenderRef ref="TEMP"/>
      <AppenderRef ref="CONSOLE"/>
    </Async>
  </Appenders>
  <Loggers>
    <Root level="debug">
      <AppenderRef ref="ASYNC"/>
    </Root>
  </Loggers>
</Configuration>

 

Guess you like

Origin www.cnblogs.com/z-x-p/p/11527976.html