乐趣区

关于log4j: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 : numis" + num);
        log.warn("8888888888888888Warning : numis" + num);
        log.debug("8888888888888888Debug : numis" + num);
        log.error("8888888888888888Error : numis" + num);
​
    }
}
退出移动版