LOG4J2+SL4J 配置使用全流程

  1. 1.文件目录:

这里写图片描述

  1. 2.pom:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.zh</groupId>
  <artifactId>logtest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>logtest</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    

  
  <!-- log配置:Log4j2 + Slf4j -->
      <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.11.0</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.11.0</version>
  </dependency>
<dependency> <!-- 桥接:告诉Slf4j使用Log4j2 -->
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.11.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-jcl</artifactId>
    <version>2.11.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>


  </dependencies>
</project>

  1. 3resource log4j2.xml内容:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
	<!-- 变量配置 -->
	<Properties>
		<Property name="log_path">./logs</Property>
	</Properties>

	<!-- appender配置 -->
	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout
				pattern="%d{yy-MM-dd HH:mm:ss}-- %X{uuid}- %m%n" />
		</Console>
		
		<!--filepattern 为新文件夹命名规则 %i 可以生成序列号名称  -->
		<RollingFile name="DailyRollingFile"
			fileName="${log_path}/zhTest.log"
			
			filePattern="${log_path}/zHTest%d{yyyy-MM-dd}-%i.log">
			<PatternLayout
				pattern="%d{yy-MM-dd HH:mm:ss} %X{uuid}-S%m%n" />

<!-- 用于确定是否应发生翻转的策略 -->
			<Policies>
				<OnStartupTriggeringPolicy />
				<CronTriggeringPolicy schedule="0 0 0 1/1 * ? *"/>
				<SizeBasedTriggeringPolicy size="20 kb" />
				<TimeBasedTriggeringPolicy />
			</Policies>
<!-- 用于确定归档文件的名称和位置的策略  ifall==&&  ifany=|| glob里面为正则表达式-->
			<DefaultRolloverStrategy>
				<Delete basePath="./logs" maxDepth="2">
					<IfAll>
						<IfAny>
							<IfLastModified age="7d" />
							<IfAccumulatedFileCount exceeds="6" />
						</IfAny>
						<IfFileName glob="zHTest20*" />
					</IfAll>
				</Delete>
			</DefaultRolloverStrategy>
		</RollingFile>
	</Appenders>
//异步日志,保留7天,每天翻转
	<RollingFile name="ZH" fileName="${log_path}/system.log"
			filePattern="${log_path}/system.log.%d{yyyy-MM-dd}">
			<PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss} %5p %X{uuid} -- %m%n" />
			<Policies>
			<CronTriggeringPolicy schedule="0 0 0 * * ? *" />
			</Policies>
			<Filters>
				<ThresholdFilter level="warn" onMatch="DENY"
					onMismatch="NEUTRAL" />
				<ThresholdFilter level="info" onMatch="ACCEPT"
					onMismatch="NEUTRAL" />
			</Filters>
			<DefaultRolloverStrategy max="7">
			 <Delete basePath="${log_path}" maxDepth="3">
			   <IfFileName glob=".log.*" />
         	 <IfLastModified age="7d" />
        </Delete>
			</DefaultRolloverStrategy>
		</RollingFile>
	
	
	<Loggers>
	     <AsyncLogger name="com.zh" level="info" additivity="false">
        <AppenderRef ref="ZH" level="info"/>
        <AppenderRef ref="ZH1" />
    </AsyncLogger>
		<Root level="info">
		     <AppenderRef ref="ZH" level="info"/>
        <AppenderRef ref="ZH1" />
			<AppenderRef ref="Console" level="info"/>
			<AppenderRef ref="DailyRollingFile" level="error"/>
		</Root>
	</Loggers>
</Configuration>
  1. 4代码:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

/**
 * Hello world!
 *
 */
public class App 
{

	 static public Logger logger = LoggerFactory.getLogger(App.class);
    public static void main( String[] args )
    {
    
    	new Thread(new Runnable() {
			
			@Override
			public void run() {
				int ii=1;
				while(true) {
//						Thread.sleep(1000);
						MDC.put("uuid", StringUtils.getUUID());
						ii++;
						logger.info( "Hello World!" );
						logger.error("haha"+ii,"haha"+ii);
	
				}
			}
		}).start();
    	
    }
}



Utils:

package com.zh.logtest;

import java.util.ArrayList;
import java.util.UUID;

public class StringUtils {
	 /** 
	    * 获得指定数目的UUID 
	    * @param number int 需要获得的UUID数量 
	    * @return String[] UUID数组 
	    */ 
	    public static ArrayList<String> getUUID(int number){
	        ArrayList<String> list=new ArrayList<>();
	    if(number < 1){ 
	    return null; 
	    } 
	    for(int i=0;i<number;i++){ 
	    list.add(getUUID()); 
	    } 
	    return list; 
	    }

	    /** 
	    * 获得一个UUID 
	    * @return String UUID 
	    */ 
	    public static String getUUID(){ 
	    String uuid = UUID.randomUUID().toString(); 
	    //去掉“-”符号 
	    return uuid.replaceAll("-", "");
	    }
}

标准日志输出如下:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
	<!-- 变量配置 -->
	<Properties>
		<Property name="log_path">./logs</Property>
	</Properties>

	<!-- appender配置 -->
	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss} %5p %X{uuid} - %m%n" />
		</Console>
		<!--filepattern 为新文件夹命名规则 %i 可以生成序列号名称 -->
		<RollingFile name="TRACE" fileName="${log_path}/trace.log"

			filePattern="${log_path}/trace.log.%d{yyyy-MM-dd}-%i.log">
			<PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss} %5p %X{uuid} - %m%n" />

			<!-- 用于确定是否应发生翻转的策略 -->
			<Policies>
				<CronTriggeringPolicy schedule="0 0 0 1/1 * ? *" />
			</Policies>


			<!-- 用于确定归档文件的名称和位置的策略 ifall==&& ifany=|| glob里面为正则表达式 -->
			<DefaultRolloverStrategy>
				<Delete basePath="./logs" maxDepth="2">
					<IfFileName glob="trace.log.*">
						<IfAny>
							<IfLastModified age="7d" />
							<IfAccumulatedFileCount exceeds="8" />
						</IfAny>
					</IfFileName>
				</Delete>
			</DefaultRolloverStrategy>
		</RollingFile>


		<!--filepattern 为新文件夹命名规则 %i 可以生成序列号名称 -->
		<RollingFile name="SYSTEM" fileName="${log_path}/system.log"

			filePattern="${log_path}/system.log.%d{yyyy-MM-dd}-%i.log">
			<PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss} %5p %X{uuid} - %m%n" />

			<!-- 用于确定是否应发生翻转的策略 -->
			<Policies>
				<CronTriggeringPolicy schedule="0 0 0 1/1 * ? *" />
			</Policies>
			<Filters>
				<ThresholdFilter level="warn" onMatch="DENY"
					onMismatch="NEUTRAL" />
				<ThresholdFilter level="info" onMatch="ACCEPT"
					onMismatch="NEUTRAL" />
					
		
			</Filters>
			<!-- 用于确定归档文件的名称和位置的策略 ifall==&& ifany=|| glob里面为正则表达式 -->
			<DefaultRolloverStrategy>
				<Delete basePath="./logs" maxDepth="2">
					<IfFileName glob="system.log.*">
						<IfAny>
							<IfLastModified age="2d" />
							<IfAccumulatedFileCount exceeds="8" />
						</IfAny>
					</IfFileName>
				</Delete>
			</DefaultRolloverStrategy>
		</RollingFile>



		<RollingFile name="ERROR" fileName="${log_path}/error.log"

			filePattern="${log_path}/error.log.%d{yyyy-MM-dd}-%i.log">
			<PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss} %5p %X{uuid} - %m%n" />

			<Policies>
				<CronTriggeringPolicy schedule="0 0 0 1/1 * ? *" />
			</Policies>

			<Filters>
				<ThresholdFilter level="error" onMatch="ACCEPT"
					onMismatch="NEUTRAL" />
				<ThresholdFilter level="trace" onMatch="DENY"
					onMismatch="NEUTRAL" />
			</Filters>
			<DefaultRolloverStrategy>
				<Delete basePath="./logs" maxDepth="2">
					<IfFileName glob="error.log.*">
						<IfAny>
							<IfLastModified age="7d" />
							<IfAccumulatedFileCount exceeds="8" />
						</IfAny>
					</IfFileName>
				</Delete>
			</DefaultRolloverStrategy>
		</RollingFile>


		<RollingFile name="AUDIT" fileName="${log_path}/audit.log"

			filePattern="${log_path}/audit.log.%d{yyyy-MM-dd}-%i.log">
			<PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss} %5p %X{uuid} - %m%n" />
			<Policies>
				<CronTriggeringPolicy schedule="0 0 0 1/1 * ? *" />
					<SizeBasedTriggeringPolicy  size=""/>
		<!-- 						<TimeBasedTriggeringPolicy /> -->
			</Policies>

			<Filters>
				<ThresholdFilter level="error" onMatch="DENY"
					onMismatch="NEUTRAL" />
				<ThresholdFilter level="warn" onMatch="ACCEPT"
					onMismatch="NEUTRAL" />
				<ThresholdFilter level="trace" onMatch="DENY"
					onMismatch="NEUTRAL" />
			</Filters>
			<DefaultRolloverStrategy>
				<Delete basePath="./logs" maxDepth="2">
					<IfFileName glob="audit.log.*">
						<IfAny>
							<IfLastModified age="7d" />
							<IfAccumulatedFileCount exceeds="8" />
						</IfAny>
					</IfFileName>
				</Delete>
			</DefaultRolloverStrategy>
		</RollingFile>
	</Appenders>
	<Loggers>
		<Root level="info">
			<AppenderRef ref="Console" level="info" />
			<AppenderRef ref="TRACE" />
			<AppenderRef ref="SYSTEM" />
			<AppenderRef ref="ERROR" />
			<AppenderRef ref="AUDIT" />
		</Root>
	</Loggers>
</Configuration>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值