Java logging Introduction (4) -Log4j2

Log4j2 is an upgraded version of Log4j compared to its predecessor Log4j 1.x provides a significant improvement, and offers many improvements offered in Logback while fixes some inherent problems Logback architecture.

Log4j2 lot of content, this paper introduces its simple and practical method; used herein to software version: Java 1.8.0_191, log4j 2.12.1.

1, the configuration

1.1, load the configuration

Log4j2 can automatically find the configuration file to configure the initialization period; in accordance with the priority to find the configuration file until you find, priority is as follows:

1, search system configuration file corresponding to the attribute log4j.configurationFile
2, look at log4j2-test.properties CLASSPATH
. 3, look log4j2-test.yaml or log4j2-test.yml at CLASSPATH
. 4, look at log4j2-test classpath. json-test.jsn or log4j2
. 5, look at the test.xml-log4j2 classpath
. 6, or find log4j2.yaml log4j2.yml the classpath
. 7, or the lookup log4j2.json log4j2.jsn the classpath
. 8, find the classpath log4j2.xml
9, if the above steps can not find the configuration file, the default configuration, log output to the console.

1.2, automatically update the configuration

If the configuration is loaded from a configuration file, by setting monitorInterval (seconds) parameter allows changes log4j2 checks files automatically, if changed from the newly loaded configuration. Check whether the file change log and the timing is more than monitorInterval time since the last inspection.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorInterval="30">
...
</Configuration>

2、Appenders

2.1 ConsoleAppender

<Console name="STDOUT">
</Console>

Log output to the console, the following common parameters:

Filter filter
layout placer
name the name of the output destination
target SYSTEM_OUT or SYSTEM_ERR; default SYSTEM_OUT.

2.2、FileAppender

<File name="File" fileName="D:\temp\a.log">
</File>

To output log file, the following common parameters:

Filter filter
fileName file name
layout placer
name output destination name

2.3、RollingFileAppender

<RollingFile name="RollingFile" fileName="D:\temp\b.log" filePattern="D:\temp\$${date:yyyy-MM}\b-%d{MM-dd-yyyy}-%i.log">
</RollingFile>

Scroll to the output log files generated by certain strategies history log file, and retain a fixed number of the latest history file; common parameters are as follows:

Filter filter
fileName file name
filePattern history log file name generation strategy, date formats supported configuration: $$ {date: yyyy-MM },% d {MM-dd-yyyy}; Configuration number:% I
layout placer
name output destination the name of the
policy history log file generation strategy
DefaultRolloverStrategy default policy

2.3.1、policy

The following strategies:

<Policies>
  <OnStartupTriggeringPolicy />
  <SizeBasedTriggeringPolicy size="20MB" />
  <TimeBasedTriggeringPolicy />
</Policies>

OnStartupTriggeringPolicy, activated when the history log file is generated, its parameters:

minSize log file is larger than the value, history log files generated at startup; default is 1, to prevent an empty log file generation history log file

SizeBasedTriggeringPolicy, history log file will be generated when the log file reaches much, its parameters:

size log file size

TimeBasedTriggeringPolicy, according to the time interval to generate a history log file, its parameters:

interval generation time a new history log file interval, in hours, the default is 1
if modulate should be adjusted interval as an interval of 4 hours, the current time is 3:00, the generation time point of the historical log file 4:00, 8:00 ...
maxRandomDelay maximum number of seconds to generate random delay history log file, the default is 0; if there are multiple applications on the same server and end time rolling log file configuration, this setting is very useful, you can spread the load to a different time .

SizeBasedTriggeringPolicy and TimeBasedTriggeringPolicy If used, it needs to be given filePattern% i, otherwise it will overwrite the original history log file, because it would not change the filename timestamp when SizeBasedTriggeringPolicy policy in effect.

2.3.2、DefaultRolloverStrategy

We have the following common parameters:

Max maximum number of historical log files

 

There are a lot of other Appender, such as JDBCAppender, JMS Appender, JPAAppender, KafkaAppender and so on, here is not introduced one by one, the document can refer to the official website: https: //logging.apache.org/log4j/2.x/manual/appenders. html

3、Layouts

log4j2 offers a variety of layout, such as HTML Layout, JSON Layout, Pattern Layout, XML Layout and so on, here we focus on Pattern Layout.

<PatternLayout pattern="%d %-p [%t] %C.%M[%F:%L] -> %m%n" />

Log4J2 formatted log information via the parameter, which is very similar to the log4j 1.x:

d {pattern}, date {pattern } date output logging events may specify the format thereafter; as:% d {dd MMM yyyy HH : mm: ss, SSS}, similar output: 02 Nov 2012 14:34: 02,781
P | {level = level label, label = level, ...}, P | {length = n-level}, P | = lowerCase to true level {|} to false priority output logging events, such as:% level { WARN = W is, the INFO = the I, length = 2}
T, TN, thread, threadName thread output generator logging events name
T, ID, the threadId ID threads generated output logging events
c {precision}, logger {precision } output class logging events; precision can be given later, such as category "org.apache.commons.Foo";% c {1 } to output "Foo",% c {1 } to output "oacFoo."
C {precision}, class {precision} output delivers fully qualified class name of the caller logging request; precision can be given back, and c {precision} similar.
M, method output delivers the name of the method logging request. The higher operating costs, may affect the nature, care.
F, file output file name sent logging request. The higher operating costs, may affect the nature, care.
L, lineOutput line numbers issued logging request. The higher operating costs, may affect the nature, care.
m {nolookups} {ansi}, msg {nolookups} {ansi}, message {nolookups} {ansi} message output application provides
n outputs associated with the internet line separator, Windows platform \ r \ n, Unix platform \ n-
X, the NDC output associated with the thread generation event logging the NDC (nested diagnostic context)
X-Key {[, key2 ...]}, {MDC Key [, key2 ...]}, the MDC Key {[ , key2 ...]} the MDC for threads associated with the generated output logging events (mapped diagnostic context). Typically used for multiple clients connected to the same server, which is easy to distinguish the client server access logs to stay. % X {5} as the recording code for the client logs 5

By default, all relevant information is output; format can be modified by, change the minimum field width, the maximum width and alignment of the field direction. Format modifying placed between conversion and the percent sign characters.

% 20c if the category name is less than 20 characters, with spaces left pad.
% -20c if the category name is less than 20 characters, with spaces the right pad.
% .30c if the category name is longer than 30 characters, starting from the left intercepted off the excess characters.
% 20.30c if the category name is less than 20 characters, with spaces left pad; if the category name is longer than 30 characters, starting from the left intercepted off the excess characters.
% -20.30c if the category name is less than 20 characters, with spaces pad and right; if the category name is longer than 30 characters, starting from the left intercepted off the excess characters.

See more instructions https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout

4、Lookups

The main function of the lookup is to provide another way to add some special values ​​to the log.

<File name="lookupTest" fileName="D:\temp\lookup.log">
    <PatternLayout pattern="$${date:yyyy-MM} $${env:PATH} ${java:runtime} ${sys:file.encoding} %d -> %m%n" />
</File>

4.1、Date Lookup

Gets the value of the current date, using SimpleDateFormat verify the format is valid; get the current day of the month, such as: $$ {date: yyyy-MM}

4.2、Environment Lookup

Get the value of the environment variable; as to obtain the value of the variable $ PATH: $$ {env: PATH}

4.3、Java Lookup

Java correlation value acquired environmental information; runtime such as access java: $ {java: runtime}

4.4、System Properties Lookup

Obtaining a value related to the system property; The encoded file acquisition system: $ {sys: file.encoding}

 

There are a lot of other Lookup, such as Context Map Lookup, Jndi Lookup, Spring Boot Lookup, etc., will not describe here, you can refer to the official website of the document: https: //logging.apache.org/log4j/2.x/manual/ lookups.html.

5、Filters

Filters are used to determine whether a log output; filter calls on either a filtering method will return a result value: ACCEPT, DENY or NEUTRAL. There are more than

<Filters>
	<RegexFilter regex="This.*" onMatch="NEUTRAL" onMismatch="DENY"/>
	<ThresholdFilter level="INFO" onMatch="NEUTRAL" onMismatch="DENY"/>
	<TimeFilter start="05:00:00" end="17:30:00" onMatch="NEUTRAL" onMismatch="DENY"/>    
</Filters>

5.1 RegexFilter

Regular expression to be compared with log message through java, determining whether filtering.

5.2、ThresholdFilter

If the level is determined by the log filter

5.3、TimeFilter

Time is judged by filtration

5.4 CompositeFilter

Combined filter, through a combination of other filters to form a filter chain.

 

There are various other Filter, such as BurstFilter, MarkerFilter and so on, here is not introduced one by one, the document can refer to the official website: https: //logging.apache.org/log4j/2.x/manual/filters.html.

6, the actual use

6.1, the configuration file log4j2.xml

The file into src / log4j2.xml or src / main / under resources (spring boot project) can be.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" strict="true" monitorInterval="30">
    <Appenders>
        <Console name="STDOUT">
            <PatternLayout pattern="%d %p [%t] %C.%M[%F:%L] -> %m%n" />
            <Filters>
                <RegexFilter regex="This.*" onMatch="NEUTRAL" onMismatch="DENY"/>
                <ThresholdFilter level="INFO" onMatch="NEUTRAL" onMismatch="DENY"/>
                <TimeFilter start="05:00:00" end="17:30:00" onMatch="NEUTRAL" onMismatch="DENY"/>    
            </Filters>
        </Console>
        <File name="File" fileName="D:\temp\a.log">
            <PatternLayout pattern="%d %-p [%t] %C.%M[%F:%L] -> %m%n" />
        </File>
        <File name="lookupTest" fileName="D:\temp\lookup.log">
            <PatternLayout pattern="$${date:yyyy-MM} $${env:PATH} ${java:runtime} ${sys:file.encoding} %d -> %m%n" />
        </File>
        <RollingFile name="RollingFile" fileName="D:\temp\b.log" filePattern="D:\temp\$${date:yyyy-MM}\b-%d{MM-dd-yyyy}-%i.log">
            <PatternLayout pattern="%d %-p [%t] %C.%M[%F:%L] -> %m%n" />
            <Policies>
                <OnStartupTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="200KB" />
                <TimeBasedTriggeringPolicy />
            </Policies>
            <DefaultRolloverStrategy max="5"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="STDOUT" />
            <AppenderRef ref="File" />
            <AppenderRef ref="lookupTest" />
            <AppenderRef ref="RollingFile" />
        </Root>
        <!-- Logger name="com.inspur" level="info"> <AppenderRef ref="File"/> </Logger -->
    </Loggers>
</Configuration>

6.2, code examples

package com.inspur.demo.log;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


/**
 * log4j2使用示例
 */
public class Log4j2Case {
    private static Logger logger = LogManager.getLogger(Log4j2Case.class);
    public static void main(String[] args) throws Exception {
        logger.debug("This is debug message.");
        logger.warn(logger.getClass());
        for (int i = 0; i < 100; i++) {
            logger.info("This is info message:" + i);
        }
    }
}

Run the code can see the console and related documents generated log messages.

Guess you like

Origin www.cnblogs.com/wuyongyin/p/12326174.html