Log4j2 + Slf4j + maven使用

一、Maven配置

<!-- log4j2 的包配合slf4j这两个包无需引入-->
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-api</artifactId>
  <version>2.19.0</version>
</dependency>
<dependency>
   <groupId>org.apache.logging.log4j</groupId>
   <artifactId>log4j-core</artifactId>
   <version>2.19.0</version>
</dependency>
<dependency>
   <groupId>org.apache.logging.log4j</groupId>
   <artifactId>log4j-slf4j-impl</artifactId>
   <version>2.19.0</version>
</dependency>

<!-- log4j2+slf4j的包 只需要引入这一个就好了-->
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-slf4j-impl</artifactId>
  <version>2.19.0</version>
</dependency>

更详细的配置请去官网查阅:https://logging.apache.org/log4j/2.x/maven-artifacts.html

二、配置log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>

<!-- 级别[ALL< Trace < DEBUG < INFO < WARN < ERROR < FATAL < OFF] -->
<!-- monitorInterval(单位s)指定log4j自动重新配置的监测间隔时间-->
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <!-- 配置日志文件输出目录 ${sys:user.home} -->
        <Property name="log_path_home">logs</Property>
    </Properties>

    <Appenders>
        <!--每日存档 关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval,
                日期格式精确到哪一位,interval也精确到哪一个单位 -->
        <RollingFile name="dailyInfoFile" fileName="${log_path_home}/info.log"
                     filePattern="${log_path_home}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <!--过滤器
			onMatch:level及以上级别的信息
			onMismatch:level以下级别的信息
			值:
			DENY:拦截
			ACCEPT:接收
			NEUTRAL:不拦截,不接收
			-->
			<!--
				只显示一种日志级别的输出的过滤方式,以下是只显示warn级别日志的例子:
				<Filters>
					顺序很重要,需要显示的日志级别放在最后
					<ThresholdFilter level="error" onMatch="DENY"
									 onMismatch="NEUTRAL" />
					<ThresholdFilter level="warn" onMatch="ACCEPT"
									 onMismatch="DENY" />
				</Filters>
			-->
            <ThresholdFilter level="info" onMatch="ACCEPT"
                             onMismatch="DENY" />
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss}[%level][%c:%L][%t] %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
                <!-- <SizeBasedTriggeringPolicy size="10 MB" />  --><!--指定每一个文件大小 -->
            </Policies>
			<DefaultRolloverStrategy max="7" /><!-- 最多保留max个历史文件-->
        </RollingFile>
		<!--每日错误日志-->
        <RollingFile name="dailyErrFile" fileName="${log_path_home}/error.log"
                     filePattern="${log_path_home}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="error" onMatch="ACCEPT"
                             onMismatch="DENY" />
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss}[%level][%c:%L][%t] %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
			<DefaultRolloverStrategy max="7" /><!-- 最多保留max个历史文件-->
        </RollingFile>
        <!--这个输出控制台的配置 -->
        <Console name="Console" target="SYSTEM_OUT">
            <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
            <ThresholdFilter level="trace" onMatch="ACCEPT"
                             onMismatch="DENY" />
            <!-- 输出日志的格式
                %d{yyyy-MM-dd HH:mm:ss.SSS} : 日志生产时间
				%level 日志等级 如:%-5level -5表示左对齐并且固定输出5个字符,如果不足在右边补0
                %p : 日志输出格式
				%t : 输出当前线程名称
                %c/%C : logger的名称/输出类名
                %m : 日志内容,即 logger.info("message")
                %n : 换行符
                %C : Java类名
                %L : 日志输出所在行数
                %M : 日志输出所在方法名
				%logger : 输出logger名称,因为Root Logger没有名称,所以没有输出
				%l: 输出完整的错误位置, 包括类名、方法名、文件名、行数
                hostName : 本地机器名
                hostAddress : 本地ip地址 -->
            <PatternLayout
                    pattern="%d{yyyy-MM-dd HH:mm:ss}[%level][%c:%L][%t] %msg%n" />
        </Console>

        <!--打印出所有信息,append属性决定每次运行程序会自动清空-->
        <!--append true表示追加记录,false表示覆盖 -->
        <File name="log" fileName="${log_path_home}/curSvrPrint.log" append="false">
            <PatternLayout
                    pattern="%d{yyyy-MM-dd HH:mm:ss}[%level][%c:%L][%t] %msg%n"/>
        </File>
       
    </Appenders>

    <!--定义了logger并引入的appender,appender才会生效-->
    <Loggers>
			<!--过滤掉无用的日志-->
<!--        <logger name="包名" level="error" />-->
        <root level="all">
            <appender-ref ref="Console"/>
            <appender-ref ref="log"/>
            <appender-ref ref="dailyInfoFile"/>
            <appender-ref ref="dailyErrFile"/>
        </root>
    </Loggers>
</Configuration>

三、配置文档加载

 关于配置文件加载,摘至官方文档的一段说明:

  1. Log4j has the ability to automatically configure itself during initialization. When Log4j starts it will locate all the ConfigurationFactory plugins and arrange them in weighted order from highest to lowest. As delivered, Log4j contains four ConfigurationFactory implementations: one for JSON, one for YAML, one for properties, and one for XML.

  2. Log4j will inspect the system property and, if set, will attempt to load the configuration using the that matches the file extension. Note that this is not restricted to a location on the local file system and may contain a URL."log4j2.configurationFile"ConfigurationFactory
  3. If no system property is set the properties ConfigurationFactory will look for in the classpath.log4j2-test.properties
  4. If no such file is found the YAML ConfigurationFactory will look for or in the classpath.log4j2-test.yamllog4j2-test.yml
  5. If no such file is found the JSON ConfigurationFactory will look for or in the classpath.log4j2-test.jsonlog4j2-test.jsn
  6. If no such file is found the XML ConfigurationFactory will look for in the classpath.log4j2-test.xml
  7. If a test file cannot be located the properties ConfigurationFactory will look for on the classpath.log4j2.properties
  8. If a properties file cannot be located the YAML ConfigurationFactory will look for or on the classpath.log4j2.yamllog4j2.yml
  9. If a YAML file cannot be located the JSON ConfigurationFactory will look for or on the classpath.log4j2.jsonlog4j2.jsn
  10. If a JSON file cannot be located the XML ConfigurationFactory will try to locate on the classpath.log4j2.xml
  11. If no configuration file could be located the will be used. This will cause logging output to go to the console.DefaultConfiguration

 四、使用方式

Logger logger = org.slf4j.LoggerFactory.getLogger(XXX.class);

  • 15
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值