Spring中使用Log4j記錄日志


以下內容引用自http://wiki.jikexueyuan.com/project/spring/logging-with-log4j.html

例子:

pom.xml:

<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.jsoft.testspring</groupId>
    <artifactId>testlog4juse</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>testlog4juse</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>

        <!-- Spring Core --> <!-- http://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- Spring Context --> <!-- http://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- Log4j --> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.1</version> </dependency>

    </dependencies>
</project>

HelloWorld.java:

package com.jsoft.testspring.testlog4juse;

public class HelloWorld {
    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    public void getMessage() {
        System.out.println("Your Message : " + message);
    }
}

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- 配置參考:http://blog.csdn.net/seven_zhao/article/details/42124131 -->
<!-- status="OFF",可以去掉,它的含義為是否記錄log4j2本身的event信息,默認是OFF -->
<configuration status="OFF">
     <!-- 定義下面的引用名 -->
     <Properties>
          <property name="log_pattern">%d{yyyy-MM-ddHH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n</property>
          <property name="basePath">c:/</property>
          <property name="file_name">${basePath}/applog/app.log</property>
          <property name="rolling_file_name">${basePath}/applog/app-%d{yyyy-MM-dd}-%i.log.gz</property>
         
          <property name="every_file_size">10M</property><!-- 日志切割的最小單位 -->
          <property name="output_log_level">debug</property><!-- 日志輸出級別 -->
     </Properties>
 
    <!--先定義所有的appender-->
    <appenders>
       <!--這個輸出控制台的配置-->
       <Console name="Console" target="SYSTEM_OUT">
           <!--控制台只輸出level及以上級別的信息(onMatch),其他的直接拒絕(onMismatch)-->
           <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/>
           <!--這個都知道是輸出日志的格式-->
           <PatternLayout pattern="${log_pattern}"/>
       </Console>
 
       <!--這個會打印出所有的信息,每次大小超過size,則這size大小的日志會自動存入按年份-月份建立的文件夾下面並進行壓縮,作為存檔-->
       <!-- 按月生成歸檔日志,可以使用filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz"-->
       <RollingFile name="RollingFile" fileName="${file_name}" filePattern="${rolling_file_name}">
           <PatternLayout pattern="${log_pattern}"/>
           <SizeBasedTriggeringPolicy size="${every_file_size}"/>
       </RollingFile>
       
       <!--如果需要配置多個Rollingfile地址,還需要在root下添加appender-ref ref="RollingFile1"/> 
        <RollingFile name="RollingFile1" fileName="logs/app1.log" filePattern="logs/app1-%d{yyyy-MM-dd}-%i.log.gz">
           <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss z}%-5level %class{36} %L %M - %msg%xEx%n"/>
           <SizeBasedTriggeringPolicy size="10MB"/>
        </RollingFile>
        -->
    </appenders>
    <!--然后定義logger,只有定義了logger並引入的appender,appender才會生效-->
    <loggers>
       <!--建立一個默認的root的logger,需要在root的level中指定輸出的級別,-->
       <root level="${output_log_level}">
           <appender-ref ref="RollingFile"/>
           <appender-ref ref="Console"/>
       </root>
 
    </loggers>
</configuration>

beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloWorld" class="com.jsoft.testspring.testlog4juse.HelloWorld">
        <property name="message" value="Hello World!" />
    </bean>

</beans>

App.java:

package com.jsoft.testspring.testlog4juse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Hello world!
 *
 */
public class App {
    static Logger log = (Logger) LogManager.getLogger(App.class.getName()); public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        log.info("Going to create HelloWord Obj");
        HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
        obj.getMessage();
        log.info("Exiting the program");
    }
}

測試結果:

 

測試工程:https://github.com/easonjim/5_java_example/tree/master/springtest/test20/testlog4juse


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM