You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot Log4j2自定义混合日志布局:Pattern与JSON结合方案求助

实现符合FileBeat要求的混合格式日志输出

核心配置方案

直接使用Log4j2的PatternLayout,在外层严格遵循FileBeat要求的格式基础上,将msg部分构造为包含指定字段的JSON结构,既满足FileBeat的识别规则,又能让Kibana解析关键字段。

以下是log4j2.xml的完整配置示例:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{ISO8601} - %-5level: {&quot;@timestamp&quot;:&quot;%d{ISO8601}&quot;,&quot;message&quot;:&quot;%encode{%message}&quot;,&quot;thread&quot;:&quot;%thread&quot;,&quot;logger_name&quot;:&quot;%logger&quot;,%if{%exception}{&quot;error.message&quot;:&quot;%encode{%exception}&quot;,&quot;error.stack_trace&quot;:&quot;%encode{%throwable{full}}&quot;}}%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

配置关键点说明

  • 外层格式匹配:严格遵循%d{ISO8601} - %-5level: %msg%n规则,确保FileBeat能正常识别日志结构
  • JSON字段控制:
    • @timestamp:与外层日志时间保持一致,用%d{ISO8601}生成
    • message:日志文本内容,通过%encode转义JSON特殊字符,避免格式错误
    • thread/logger_name:可选的上下文字段,可根据业务需求增删
    • error.message/error.stack_trace:通过%if{%exception}实现条件输出,仅当存在异常时才添加,保证JSON结构合法;%throwable{full}输出完整异常栈轨迹
  • 异常处理:%encode处理异常信息中的特殊字符,避免JSON解析失败

Spring Boot依赖调整

确保项目使用Log4j2作为日志框架,排除默认的Logback:

Maven项目

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

Gradle项目

configurations {
    all {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
}
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-log4j2'
}

验证效果

启动应用后,控制台输出的日志格式如下:

2024-05-20T14:30:00,123+08:00 - INFO : {"@timestamp":"2024-05-20T14:30:00,123+08:00","message":"处理Kafka消息完成","thread":"kafka-consumer-1","logger_name":"com.example.KafkaMessageListener"}
2024-05-20T14:30:05,456+08:00 - ERROR: {"@timestamp":"2024-05-20T14:30:05,456+08:00","message":"处理消息失败","thread":"kafka-consumer-1","logger_name":"com.example.KafkaMessageListener","error.message":"NullPointerException: 空指针异常","error.stack_trace":"java.lang.NullPointerException: 空指针异常\n\tat com.example.KafkaMessageListener.processMessage(KafkaMessageListener.java:42)\n\t..."}

该格式既被FileBeat正常采集,又能在Kibana中通过error.stack_trace等关键字段进行过滤分析。

内容的提问来源于stack exchange,提问作者Chaitanya Adabala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 13:50:20