log4j升级到log4j2 ( 项目中使用slf4j )

玄机

目前市面中使用的大多数是spring boot项目,下面我说的方案sring也适用。
在这里给大家推荐一套目前 最火的Java后端日志框架方案
门户日志用:slf4j
日志实现用:log4j2

具体的配置或者优化如下详情
1、导入依赖
log4j2应尽量使用同一版本,否则可能出现不兼容的情况

    // log升级配置
    compile('org.apache.logging.log4j:log4j-1.2-api:2.9.1')
    compile('org.apache.logging.log4j:log4j-web:2.9.1')
    compile('org.apache.logging.log4j:log4j-core:2.9.1')
    compile('org.apache.logging.log4j:log4j-api:2.9.1')
    // log
    // compile('log4j:log4j:1.2.17')
    compile('org.slf4j:slf4j-api:1.6.6')
    compile('org.slf4j:slf4j-log4j12:1.7.21')

2、创建log4j2.properties
(如果有log4j.properties要删除的)
(下面还有一种使用log4j.xml的方法,两种任选其一,现在是倾向于用xml)

status = warn
name = MyApp

#指定输出源‘类型’为控制台
appender.console.type = Console
appender.console.name = consoleLogDemo
appender.console.filter.threshold.type = ThresholdFilter
appender.console.filter.threshold.level = debug
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5p] [%d{yyyy-MM-dd HH:mm:ss}] [%C{1}:%M:%L] %m%n
appender.console.target = System_out

appender.rolling.type = RollingFile
appender.rolling.name = fileLogDemo
appender.rolling.filter.threshold.type = ThresholdFilter
appender.rolling.filter.threshold.level = info
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = [%-5p] [%d{yyyy-MM-dd HH:mm:ss}] [%C{1}:%M:%L] %m%n
appender.rolling.append = true
appender.rolling.fileName =/data/logs/workflow/web.log
appender.rolling.filePattern=/data/logs/wokflow/web.log.%d{yyyy-MM-dd}
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 2
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=100MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 5

logger.rolling.name = com.XXX
logger.rolling.level = info
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = fileLogDemo

#指明根级日志的级别
rootLogger.level = info
#指定哪些appender输出源是根级日志的输出级别
rootLogger.appenderRef.consolelogdemo.ref = consoleLogDemo
rootLogger.appenderRef.filelogdemo.ref = fileLogDemo

3、log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别按照从低到高为:ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF -->
<!--status="WARN" :用于设置log4j2自身内部日志的信息输出级别,默认是OFF-->
<Configuration status="WARN" monitorInterval="30">
    <!--自定义一些常量,之后使用${变量名}引用-->
    <properties>
        <property name="LOG_PATH">D:/logs</property>
        <property name="PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] [%l] %p - %m%n%n"/>
        <property name="INFO_LOG">info</property>
        <property name="DEBUG_LOG">debug</property>
        <property name="ERROR_LOG">error</property>
    </properties>
    <!--appenders:定义输出内容,输出格式,输出方式,日志保存策略等,常用其下三种标签[console,File,RollingFile]-->
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>

        <RollingFile name="DebugAppender" fileName="${LOG_PATH}/${DEBUG_LOG}.log"
                     filePattern="${LOG_PATH}/$${date:yyyy-MM}/debug-%d{yyyy-MM-dd}-%i.log"
                     immediateFlush="true">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
            <Filters>
                <ThresholdFilter level="INFO" onMatch="DENY" onMismatch="NEUTRAL"/>
                <ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <PatternLayout pattern="${PATTERN}" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="10 MB" />
            </Policies>
            <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

        <RollingFile name="InfoAppender" fileName="${LOG_PATH}/${INFO_LOG}.log"
                     filePattern="${LOG_PATH}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log"
                     immediateFlush="true">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
            <Filters>
                <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL" />
                <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <PatternLayout pattern="${PATTERN}" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <!-- SizeBasedTriggeringPolicy :文件大小滚动策略-->
                <SizeBasedTriggeringPolicy size="10 MB" />
            </Policies>
            <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

        <RollingFile name="ErrorAppender" fileName="${LOG_PATH}/${ERROR_LOG}.log"
                     filePattern="${LOG_PATH}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log"
                     immediateFlush="true">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
            <Filters>
                <ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <PatternLayout pattern="${PATTERN}" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="10 MB" />
            </Policies>
            <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

    </Appenders>
    <!--定义logger,只有定义了logger并引入的appender,appender才会生效-->
    <Loggers>
        <!--Logger节点用来单独指定日志的形式,name为包路径,比如要为org.springframework包下所有日志指定为ERROR级别等。 -->
        <logger name="org.apache.ibatis" additivity="false" level="ERROR" />
        <logger name="org.apache.shiro" additivity="false" level="ERROR" />
        <logger name="net.sf.ehcache" additivity="false" level="ERROR" />
        <logger name="org.apache.commons" additivity="false" level="ERROR" />
        <logger name="org.mybatis.spring" additivity="false" level="ERROR" />
        <logger name="java.sql" additivity="false" level="ERROR" />
        <logger name="org.springframework" additivity="false" level="ERROR" />
        <logger name="com.alibaba.druid.filter.stat" additivity="false" level="WARN" />
        <logger name="com.alibaba.druid.pool" additivity="false" level="WARN" />
        <logger name="druid.sql.Connection" additivity="false" level="WARN" />
        <logger name="druid.sql.DataSource" additivity="false" level="WARN" />
        <logger name="druid.sql.ResultSet" additivity="false" level="WARN" />
        <logger name="druid.sql.Statement" additivity="false" level="WARN" />

        <!-- Root节点用来指定项目的根日志,如果没有单独指定Logger,那么就会默认使用该Root日志输出 -->
        <Root level="INFO">
            <AppenderRef ref="Console" />
            <AppenderRef ref="DebugAppender" />
            <AppenderRef ref="InfoAppender" />
            <AppenderRef ref="ErrorAppender" />
        </Root>
    </Loggers>
</Configuration>

如果你的项目中使用的是老的框架,使用的是web.xml,那还要去修改
4、修改web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
     <!--日志升级开始-->
    <listener>
        <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
    </listener>
    <filter>
        <filter-name>log4jServletFilter</filter-name>
        <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>log4jServletFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>
    <context-param>
        <param-name>log4jContextName</param-name>
        <param-value>myApplication</param-value>
    </context-param>
    <context-param>
        <param-name>log4jConfiguration</param-name>
        <param-value>classpath:log4j2.properties</param-value>
    </context-param>
    <!--日志升级结束-->

在web.xml中移除旧的log4j.property的配置

 <context-param>
      <param-name>log4jConfigLocation</param-name>
      <param-value>classpath:log4j.properties</param-value>
 </context-param>

5、log4j2测试
使用的LogManager.getLogger(Object.class)方式获取对象

加入测试类,并运行。如在项目磁盘目录下正常输出日志内容则说明log4j2添加成功

public class TestLogger {
    private static final Logger log = LoggerFactory.getLogger(TestLogger.class);
    public static void main(String[] args) {
        int num=10;
        log.info("8888888888888888Info : num is " + num);
        log.warn("8888888888888888Warning : num is " + num);
        log.error("8888888888888888Error : num is " + num);
​
    }
}
阅读 403

希望来这里认识更多志同道合的朋友,大家一起交流学习!

35 声望
10 粉丝
0 条评论
你知道吗?

希望来这里认识更多志同道合的朋友,大家一起交流学习!

35 声望
10 粉丝
文章目录
宣传栏