slf4j 与 log4j2 基本用法

简单的说 log4j2 是log4j的升级版,解决了部分性能和死锁问题,其使用方式与使用配置与log4j相同。

建议使用maven依赖直接使用log4j2

     <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.22.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.22.0</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.22.0</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

 

posted @ 2017-05-17 00:00  haiyupeter  阅读(2875)  评论(0编辑  收藏  举报