slf4j 與 log4j2 基本用法


簡單的說 log4j2 是log4j的升級版,解決了部分性能和死鎖問題,其使用方式與使用配置與log4j相同。

建議使用maven依賴直接使用log4j2

     <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.5</version>
        </dependency>

獲取logger實例的方法為

Logger logger = LogManager.getLogger(Test.class);

logger的基本配置如下(參考SeanXiao)

<?xml version="1.0" encoding="UTF-8"?>
<!-- log4j2使用說明(create By SeanXiao    ):
使用方式如下:
private static final Logger logger = LogManager.getLogger(實際類名.class.getName());

2、日志說明:
(1)請根據實際情況配置各項參數
(2)需要注意日志文件備份數和日志文件大小,注意預留目錄空間
(3)實際部署的時候backupFilePatch變量需要修改成linux目錄
 -->
<configuration status="error">
    <Properties>
        <Property name="fileName">front.log</Property>
        <Property name="backupFilePatch">d:/usr/front/log/</Property>
      </Properties>
    <!--先定義所有的appender-->
    <appenders>
        <!--這個輸出控制台的配置-->
        <Console name="Console" target="SYSTEM_OUT">
             <!--控制台只輸出level及以上級別的信息(onMatch),其他的直接拒絕(onMismatch)-->
            <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY" />
            <!--這個都知道是輸出日志的格式-->
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n" />
        </Console>
        
        <!--這個會打印出所有的信息,每次大小超過size,則這size大小的日志會自動存入按年份-月份建立的文件夾下面並進行壓縮,作為存檔-->
        <RollingFile name="RollingFile" fileName="${backupFilePatch}/${fileName}"
            filePattern="${backupFilePatch}$${date:yyyy-MM}/app-%d{yyyyMMddHHmmssSSS}.log.gz">
            <PatternLayout
                pattern="%d{yyyy.MM.dd 'at' HH:mm:ss.SSS z} %-5level %class{36} %L %M - %msg%xEx%n" />
            
            <!-- 日志文件大小 -->
            <SizeBasedTriggeringPolicy size="20MB" />
            <!-- 最多保留文件數 -->
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
    </appenders>
    
    <!--然后定義logger,只有定義了logger並引入的appender,appender才會生效-->
    <loggers>
        <!--建立一個logger,此logger監聽name對應的包名下的日志輸出,level表示日志級別-->
        <Logger name="com.testlog" level="trace"
            additivity="true">
            <AppenderRef ref="RollingFile" />
        </Logger>
<!--建立一個默認的root的logger-->
<Root level="error">
<AppenderRef ref="Console" />
</Root>
 </loggers> </configuration>

appenders 用於定義日志的格式,包含了Console 和 RollingFile 兩種格式,分別

Console的level是trace,而RollingFile沒有定義自己的日志級別level,由引用的loggers定義

loggers 真正的將appdender應用生效,log4j2根據Logger和Root的定義寫入相應的appender格式的日志

例子

package com.testlog;

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


public class Test {
    
    public static void main(String [] args) {
        Logger logger = LogManager.getLogger(Test.class);
        logger.error("error accu");
        logger.info("test");
        
    }
}

控制台日志

23:50:47.551 ERROR testlog.Test 11 main - error accu
23:50:47.551 INFO  testlog.Test 12 main - test

日志文件

2017.05.16 at 23:50:47.551 CST ERROR testlog.Test 11 main - error accu
2017.05.16 at 23:50:47.551 CST INFO  testlog.Test 12 main - test

日志級別:

    trace: 是追蹤,就是程序推進以下,你就可以寫個trace輸出,所以trace應該會特別多,不過沒關系,我們可以設置最低日志級別不讓他輸出。

    debug: 調試么,我一般就只用這個作為最低級別,trace壓根不用。是在沒辦法就用eclipse或者idea的debug功能就好了么。

    info: 輸出一下你感興趣的或者重要的信息,這個用的最多了。

    warn: 有些信息不是錯誤信息,但是也要給程序員的一些提示,類似於eclipse中代碼的驗證不是有error 和warn(不算錯誤但是也請注意,比如以下depressed的方法)。

    error: 錯誤信息。用的也比較多。

    fatal: 級別比較高了。重大錯誤,這種級別你可以直接停止程序了,是不應該出現的錯誤么!不用那么緊張,其實就是一個程度的問題。

 

部分系統使用了slf4j,此時可以將引用庫統一使用log4j2作為底層實現,保證日志的統一

slf4j maven

      <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.0.2</version>
        </dependency>

 

引用方式

package com.testlog;

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



public class Test {
    
    public static void main(String [] args) {
        Logger logger = LoggerFactory.getLogger(Test.class);
        logger.error("error accu");
        logger.info("test");
        
    }
}

打出的日志與log4j2的日志相同

 

apache log4j2配置文件配置說明

http://logging.apache.org/log4j/2.x/manual/configuration.html

 

舉個例子Spring中引用slf4j替換其原本的common-logging的方式

 

        <!-- springframe start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.2.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <!-- 用於適配spring中的common-logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.25</version>
        </dependency>

 

Spring標准配置

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

    <context:component-scan base-package="com.ingchat" />

</beans>

 

將log4j2.xml中的Root更改為trace,用於查看Spring中的日志

<!--然后定義logger,只有定義了logger並引入的appender,appender才會生效-->
    <loggers>
        <!--建立一個默認的root的logger-->
        <Logger name="com.ingchat.testlog" level="trace"
            additivity="true">
            <AppenderRef ref="RollingFile" />
        </Logger>
<!-- 此處更改為trace -->
<Root level="trace"> <AppenderRef ref="Console" /> </Root> </loggers>

Java代碼如下所示

package com.ingchat.testlog;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

/**
 * Hello world!
 *
 */
@Component
public class App {
    private Logger logger = LoggerFactory.getLogger(App.class);
    public void show() {
        logger.error("error accu 333");
        logger.info("test 444");
    }
    
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        App app = ctx.getBean(App.class);
        app.show();
        System.out.println("Hello World!");
    }
}

打出的日志如下15:29:12.028 DEBUG org.springframework.core.env.MutablePropertySources 109 addLast - Adding [systemProperties] PropertySource with lowest search precedence

15:29:12.033 DEBUG org.springframework.core.env.MutablePropertySources 109 addLast - Adding [systemEnvironment] PropertySource with lowest search precedence 15:29:12.033 DEBUG org.springframework.core.env.AbstractEnvironment 127 <init> - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment] ......
15:29:12.376 TRACE org.springframework.core.io.support.SpringFactoriesLoader 89 loadFactories - Loaded [org.springframework.beans.BeanInfoFactory] names: [org.springframework.beans.ExtendedBeanInfoFactory] 15:29:12.377 TRACE org.springframework.beans.CachedIntrospectionResults 265 <init> - Getting BeanInfo for class [com.ingchat.testlog.App] 15:29:12.381 TRACE org.springframework.beans.CachedIntrospectionResults 284 <init> - Caching PropertyDescriptors for class [com.ingchat.testlog.App] 15:29:12.381 TRACE org.springframework.beans.CachedIntrospectionResults 297 <init> - Found bean property 'class' of type [java.lang.Class] ...... 15:29:12.424 TRACE org.springframework.context.support.AbstractApplicationContext 362 publishEvent - Publishing event in org.springframework.context.support.ClassPathXmlApplicationContext@3d7bcb17: org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@3d7bcb17: startup date [Wed May 17 15:29:12 CST 2017]; root of context hierarchy] 15:29:12.427 TRACE org.springframework.core.env.PropertySourcesPropertyResolver 78 getProperty - Searching for key 'spring.liveBeansView.mbeanDomain' in [systemProperties] 15:29:12.427 TRACE org.springframework.core.env.PropertySourcesPropertyResolver 78 getProperty - Searching for key 'spring.liveBeansView.mbeanDomain' in [systemEnvironment] 15:29:12.427 DEBUG org.springframework.core.env.PropertySourcesPropertyResolver 91 getProperty - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source 15:29:12.429 DEBUG org.springframework.beans.factory.support.AbstractBeanFactory 251 doGetBean - Returning cached instance of singleton bean 'app' 15:29:12.430 ERROR com.ingchat.testlog.App 17 show - error accu 333 15:29:12.430 INFO com.ingchat.testlog.App 18 show - test 444 Hello World!

 

可參考http://www.cnblogs.com/yinz/p/5695995.html

 

本文參考:

http://blog.csdn.net/clementad/article/details/44625787

http://blog.csdn.net/lu8000/article/details/25754415

 

log4j2配置詳細說明

https://www.cnblogs.com/kevin-yuan/archive/2012/11/23/2784610.html

 


免責聲明!

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



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