log4j2使用

项目做了次升级,由log4j升级到了log4j2,记录一下基本的配置。

1. 引入Jar包

<dependency>
    <groupId>org.apache.logging.log4jgroupId>
    <artifactId>log4j-coreartifactId>
    <version>2.8.2version>
dependency>
<dependency>
    <groupId>org.apache.logging.log4jgroupId>
    <artifactId>log4j-apiartifactId>
    <version>2.8.2version>
dependency>

2. 添加配置文件
在资源目录下添加log4j2.xml文件。

   

<configuration status="OFF" monitorInterval="30">  
  
  <Properties>  
    <Property name="log.path">/data/logsProperty>  
  Properties>

  <appenders>  
    
    <Console name="Console" target="SYSTEM_OUT">  
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>  
    Console>  
    
    <RollingFile  name="log" fileName="${log.path}/log.log" filePattern="${log.path}/$${date:yyyy-MM}/log-%d{yyyy-MM-dd}-%i.log">
      
      <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
      <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
      <Policies>
        <TimeBasedTriggeringPolicy/>
        <SizeBasedTriggeringPolicy size="100 MB"/>
      Policies>
    RollingFile >
    
    <File name="ERROR" fileName="${log.path}/error.log">
      <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
      <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
    File>
    
    <File name="result" fileName="${log.path}/result.txt" append="false">
      <PatternLayout pattern="%msg%xEx%n"/>
    File>
  appenders>  
  <loggers>  
    
    <logger name="start" level="trace" additivity="false">
       <appender-ref ref="result"/>
       <appender-ref ref="Console"/> 
    logger>
    
    <root level="trace">  
      <appender-ref ref="log" />
      <appender-ref ref="ERROR" />
      <appender-ref ref="Console"/>  
    root>  
  loggers>  
configuration>

3. 使用

 public static Logger start= LogManager.getLogger("start"); 
 public static Logger log= LogManager.getLogger(XXX.class.getClassName()); 
 start.info("test start");
 log.info("test log");

“test start”会在控制台和result.txt中打印;
“test log”会在控制台和log.log中打印。

你可能感兴趣的:(java)