Slf4j+Log4j简单使用

Slf4j+Log4j简单使用

一、引入依赖

<dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.36</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
        <version>2.23.1</version>
    </dependency>
</dependencies>

二、配置 log4j2.xml

2.1 配置结构

在这里插入图片描述

2.2 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns="http://logging.apache.org/log4j/2.0/config" status="TRACE" monitorInterval="30">
    <Properties>
        <Property name="PROJECT_NAME">log4j2-example</Property>
        <Property name="LOG_PATH">./data/logs</Property>
        <Property name="pattern">[%d{yyyy-MM-dd HH:mm:ss,SSS}] [%c{1.}::%M] [%t] [%p]: %m%n</Property>
    </Properties>

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="${pattern}"/>
        </Console>
        <RollingFile name="RollingFile" fileName="${LOG_PATH}/${PROJECT_NAME}.log"
                     filePattern="${LOG_PATH}/${date:yyyy-MM-dd}/${PROJECT_NAME}-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout pattern="${pattern}"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="info">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFile"/>
        </Root>
    </Loggers>
</Configuration>

三、使用

package com.chenjiacheng.log.log4j2.log;

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

/**
 * Created by chenjiacheng on 2024/4/11 22:59
 *
 * @author chenjiacheng
 * @since 1.0.0
 */
public class Log4j2Example {
    private static final Logger log = LoggerFactory.getLogger(Log4j2Example.class);
    public static void main(String[] args) {
        log.trace("hello,world");
        log.debug("hello,world");
        log.info("hello,world");
        log.warn("hello,world");
        log.error("hello,world");
    }
}

四、使用MDC完成日志ID

4.1 程序入口处

MDC.put("logId", UUID.randomUUID().toString());

4.2 配置文件配置打印

<PatternLayout pattern="[%d{yyyy-MM-dd HH:mm:ss,SSS}] [%c{1.}::%M] [%t] [%p] [%X{logId}]: %m%n"/>

%x{key}: 用于打印MDC内指定Key的值。

4.3 多线程日志ID传递配置

添加配置: resources/log4j2.component.properties

isThreadContextMapInheritable=true

五. 官网

Slf4j: Slf4j
Log4j2: Log4j2

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值