Log4j2 configuration and customization

Keywords: Attribute log4j Mybatis SQL

The new requirements need to make some customized things on log4j, so the log4j2 is supplemented

To configure

Let's look at the traditional configuration of log4j2

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
  <properties>
    <property name="log_path">C:/</property>
    <property name="file_name">file.log</property>
    <property name="root_level">error</property>
  </properties>

  <Appenders>
	<!--console :Configuration of console output-->
    <Console name="Console" target="SYSTEM_OUT">
    	<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>

	<!--File :Synchronize output log to local file append:Append or not-->
    <File name="log" fileName="${logFilePath}/${logFileName}" append="false">
    	<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
    </File>
	<!--RollingFile: Log scrolling policy-->
    <RollingFile name="RollingFileInfo" fileName="${sys:user.home}/logs/info.log"
             filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
	    <!--ThresholdFilter :Log output filtering-->
	    <!--level="info" :log level,onMatch="ACCEPT" :Level in info Accept above,onMismatch="DENY" :Level in info Reject below-->
	    <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
	    <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
	    <!-- Policies :Log scrolling policy-->
	    <Policies>
	        <!-- TimeBasedTriggeringPolicy :Time rolling strategy,Generate new files by default 0:00,interval="6" : Custom file rollover interval,Generate new documents every 6 hours, modulate="true" : Whether the generated file is offset by 0,That is the 6 point.,12 spot,18 spot,0 spot-->
	        <TimeBasedTriggeringPolicy interval="6" modulate="true"/>
	        <!-- SizeBasedTriggeringPolicy :File size scrolling policy-->
	        <SizeBasedTriggeringPolicy size="100 MB"/>
	    </Policies>
	    <!-- DefaultRolloverStrategy If the property is not set, the default value is at most 7 files in the same folder. Here, 20 files are set -->
	    <DefaultRolloverStrategy max="20"/>
    </RollingFile>
  </Appenders>
  
  <Loggers>
	<Root level="${root_level}">
	  <AppenderRef ref="Console"/>
	</Root>
	<!--To configure Mybatis Sql Statement printing-->
    <logger name="com.demo.mapper" level="debug" additivity="false">
    	<AppenderRef ref="Console"/>
	</logger>
  </Loggers>
</Configuration>

The configuration mainly includes the following nodes

  • Configuration
    • properties
      • property
    • Appenders
      • Console
      • File
      • RollingFile
    • Loggers
      • Logger
      • Root

Configuration tab

The root tag of the log. Introduction to the main properties

Attribute name describe
monitorInterval Regularly scan the log configuration and dynamically change the log configuration. Parameter is second, minimum value is 5
name Log configuration name
status Set log internal print level
strict Log mode
schema Specify document constraints

Properties

The property values to be used in the log file are set through the sub label < property >

property

It is used to set the property values that may be used in the log, such as in the configuration file

<property name="log_path">C:/</property>

When configuring other properties, you can get them through ${log_path}.

Appenders

It contains multiple < appender > sub tags, which are used to specify the output location and format level of the log, such as < console > to print the log to the console.

Console

<Console name="Console" target="SYSTEM_OUT">
    <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
Attribute name describe
name Configuration name
target "System out" or "system out", the default is "system out"
Child node
  • PatternLayout: log output style settings

File

Define the file to export to the specified location,

<File name="log" fileName="${logFilePath}/${logFileName}" append="false">
    <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
</File>
Attribute name describe
name Configuration name
fileName Log output log file name
append Append output to file or not

RollingFile

Output log file policy, which can compress and store historical logs

Attribute name describe
name Configuration name
fileName Log file name
filePattern Specify the name format of the new log file
Child node
  • ThresholdFilter: filter log level filter
  • PatternLayout: log output style
  • Policies: Specifies the rolling log policy, when to create a new log file and output the log
    • Timebasedtriggingpolicy: Specifies the log rolling interval. The interval property specifies the interval. The default value is 1 hour. modulate property, whether to use 0 point as the standard time
    • Sizebased triggingpolicy: Specifies the rolling policy of log file size. The size property is used to define the size of each log file
    • Defaultrollover strategy: Specifies the log file overwrite policy. By default, 7 files under the same folder are overwritten and the old log files are deleted. The max attribute defines the maximum number of files

Loggers

Contains a default log output and multiple other optional log outputs, usually including Root and Logger nodes

Root

The Root node is used to specify the Root log of the project. If the Logger is not specified separately, the Root log output will be used by default. The required label

<Root level="${root_level}">
  <AppenderRef ref="Console"/>
</Root>
Attribute name describe
level Log output level, all < trace < debug < info < warn < error < fatal < off
Child node
  • AppenderRef: Specifies the log output Appender

Logger

The child node of Loggers, which is used to specify the form of logs separately

<!--To configure Mybatis Sql Statement printing-->
<logger name="com.demo.mapper" level="debug" additivity="false">
	<AppenderRef ref="Console"/>
</logger>
Attribute name describe
name Must specify the specific log to print, usually the package path
level Log output level, optional, default to ERROR level
additivity Whether to inherit other log output, the log may be printed in Root. Optional, default is false
Child node
  • AppenderRef: Specifies the log output Appender, or inherits Root if not specified

Custom Appender

In most cases, the Appender provided by Log4j2 can meet the business requirements. Of course, if you want to customize the output location and mode of the log, you can customize the Appender mode. The following code shows how to implement the custom Appender by inheriting the AbstractAppender class

@Plugin(name="DefineAppender",category = "Core",elementType = "appender",printObject = true)
public class DefineAppender extends AbstractAppender {
	
	//Custom configuration item
    private String fileName;

    protected DefineAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions,String fileName) {
        super(name, filter, layout, ignoreExceptions);
		//Custom configuration item
        this.fileName = fileName;
    }

    @Override
    public void append(LogEvent logEvent) {
           //The business logic of user-defined log is implemented here

    }

	
    @PluginFactory
    public static DefineAppender createAppender(@PluginAttribute("name") String name,
                                                    @PluginElement("Filter") final Filter filter,
                                                    @PluginElement("Layout") Layout<? extends Serializable> layout,
                                                    @PluginAttribute("ignoreExceptions") boolean ignoreExceptions,
                                                    @PluginAttribute("filename") String fileName) {
        if (name == null) {
            LOGGER.error("No name defiend in conf");
            return null;
        }
        if (layout == null) {
            layout = PatternLayout.createDefaultLayout();
        }
        return new DefineAppender(name, filter, layout, ignoreExceptions,fileName);


    }
}

Filter

Log filter: you can filter the logs you want to output by configuring the filter. The logs that meet the conditions can be passed by the current filter and enter the subsequent processing. log4j2 provides a variety of logs.
For example, threshold filter filters filter logs of different levels

<ThresholdFilter level="TRACE" onMatch="ACCEPT" onMismatch="DENY"/>
parameter describe
level Set filter log level
onMatch Meet the level, and determine whether to print the log according to the parameter value
onMismatch If the level is not satisfied, filter the log according to the parameter value

onMatch and onMisMatch use three parameter values, namely, accept, deny and near.

  • onMatch = "ACCEPT" indicates matching the level and above
  • onMatch = "DENY" indicates that the level and above are not matched
  • onMatch = "NEUTRAL" indicates that the level and above are handled by the next filter. If the current level is the last, it indicates that the level and above are matched
  • onMismatch = "ACCEPT" indicates matching below this level
  • onMismatch = "NEUTRAL" indicates that those at or below this level are processed by the next filter. If they are currently the last, they do not match those below this level
  • onMismatch = "DENY" indicates that the

Other filters can refer to Log4j2 filter

Custom filter

A log probability output filter is customized.
You can inherit AbstractFilter when you need a custom filter

@Plugin(name = "LogRateFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
public class LogRateFilter extends AbstractFilter {

	//Custom configuration item
    private final Double rate;

    private LogRateFilter(final Double rate,final Result onMatch,final Result onMismatch){
        super(onMatch,onMismatch);
		// Custom configuration item
        this.rate = rate;
    }

    @PluginFactory
    public static LogRateFilter createFilter(
            @PluginAttribute("rate") Double rate,
            @PluginAttribute("onMatch") final Result match,
            @PluginAttribute("onMismatch") final Result mismatch){

        final Double actuaRate = rate == 0.0 ? 1.0:rate;
        final Result onMatch = match == null ? Result.NEUTRAL : match;
        final Result onMismatch = mismatch == null ? Result.DENY : mismatch;
        return new LogRateFilter(rate,onMatch,onMismatch);
    }


    public Result filter(Level level){
        // Implement business according to log level
        Random random = new Random();
        double seed = random.nextDouble();
        System.out.println(seed);
        return seed <= rate ?  onMatch:onMismatch;
    }

    @Override
    public Result filter(final LogEvent event) {
        return filter(event.getLevel());
    }

    @Override
    public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
                         final Throwable t) {
        return filter(level);
    }

    @Override
    public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg,
                         final Throwable t) {
        return filter(level);
    }

    @Override
    public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
                         final Object... params) {
        return filter(level);
    }

}

Use
The user-defined filter in the project needs to load Log4j into the configuration configuration configuration package directory. Multiple directories are used to split

<configuration monitorInterval="5"  packages="com.demo.log4j2.config">
    <console name="Console" target="SYSTEM_OUT">
    	<!--Format of output log-->
    	<PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
    	<!-- rate:Log output probability 50% -->
    	<LogRateFilter rate="0.5" />
    </console>
</configuration>

Reference resources:
log4j2 custom Appender (output to file / RPC service)

Published 13 original articles, won praise 1, visited 4048
Private letter follow

Posted by fluteflute on Fri, 17 Jan 2020 03:18:16 -0800