4

我正在使用 spring-boot 并使用 logback 来生成日志。现在我想在每个日志中记录一个特定的标题。

我怎样才能做到这一点。

我的 logback 文件是

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <springProperty name="appName" source="spring.application.name" defaultValue="apigateway" />
    <property name="LOG_PATH" value="${LOG_PATH}" />
    <!-- Console logging -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>
                [%d{YYYY-MM-dd HH:mm:ss.SSS}] [%X{X-B3-CONVID:-}] [%X{X-B3-TraceId:-}] [%X{X-B3-SpanId:-}] [${HOSTNAME}] [%level] [${appName}] [%logger{36}.%M] - %msg %n
            </pattern>
        </encoder>
    </appender>

    <appender name="APPLICATIONLOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_PATH}/applogs/application.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>60</maxHistory>
            <totalSizeCap>20GB</totalSizeCap>
        </rollingPolicy>

        <encoder>
            <Pattern>
                [%d{YYYY-MM-dd HH:mm:ss.SSS}] [%X{X-B3-CONVID:-}] [%X{X-B3-TraceId:-}] [%X{X-B3-SpanId:-}] [${HOSTNAME}] [%level] [${appName}] [%logger{36}.%M] - %msg %n
            </Pattern>
        </encoder>
    </appender>


    <!-- set logger level: e.g. info, trace, debug, error -->
    <root level="info">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="APPLICATIONLOG" />
    </root>

</configuration>

除此之外,我没有做任何事情来配置日志。刚刚添加了 slf4j 的依赖,然后添加了 logback spring 文件。

任何帮助表示赞赏

4

2 回答 2

3

添加[%X{TrasactionId}]您的控制台和文件附加器模式,例如

对于 STDOUT 附加程序

<pattern>
   [%d{YYYY-MM-dd HH:mm:ss.SSS}] [%X{TrasactionId}] [%X{X-B3-CONVID:-}] [%X{X-B3-TraceId:-}] [%X{X-B3-SpanId:-}] [${HOSTNAME}] [%level] [${appName}] [%logger{36}.%M] - %msg %n
</pattern>

对于 APPLICATIONLOG 附加程序

<Pattern>
   [%d{YYYY-MM-dd HH:mm:ss.SSS}] [%X{TrasactionId}] [%X{X-B3-CONVID:-}] [%X{X-B3-TraceId:-}] [%X{X-B3-SpanId:-}] [${HOSTNAME}] [%level] [${appName}] [%logger{36}.%M] - %msg %n
</Pattern>

和项目中的以下代码。

import org.slf4j.MDC;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Response;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ClientFilter implements ContainerRequestFilter, ContainerResponseFilter {

    private final String TRANSACTION_ID = "TrasactionId"; 
    @Override
    public void filter(ContainerRequestContext requestContext) {
        final String transactionId = requestContext.getHeaderString(TRANSACTION_ID);
        if (transactionId == null || transactionId == "") {
            log.debug("transactionId is null/empty");
            return;
        }
        MDC.put(TRANSACTION_ID, TRANSACTION_ID + ":" + transactionId);
        // other logic based on this based on your requirement
    }

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
        final String transactionId = requestContext.getHeaderString(TRANSACTION_ID);
        if (transactionId == null || transactionId == "") {
            return;
        }
        responseContext.getHeaders().add(TRANSACTION_ID, transactionId);
        MDC.remove(TRANSACTION_ID);
    }

}

这将添加如下日志以及其他文本

[2018-06-20 11:37:31.638] [TrasactionId:75c2f962-fcdc-452e-bf7e-eddc6453673e] [6e2260ca8c4f51e4] [6e2260ca8c4f51e4] [serverName] [ERROR] [apigateway [c.s.u.c.PerformanceMetricsLogger.logRequestsWithTimeGreaterThanThreshold] - Monitoring Data : API response time : Service : apigateway, API : commonapi/v1/info/getHamburgerData

笔记:

  1. 确保标头值与 相同TrasactionId,或在任何地方添加相同的字符串以使其工作。

  2. 注册客户到球衣jersey.register(ClientFilter.class);

于 2018-06-20T09:17:57.277 回答
0

请在下面找到 Spring 示例

如果要记录 http 标头,则需要使用 MDC 功能: http: //logback.qos.ch/manual/mdc.html

创建过滤器:

@Component
class RequestHeaderFilterConfig : Filter {

    private val xRequestId = "X-Request-Id"

    override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain?) {
        val httpRequest = request as HttpServletRequest
        MDC.put(xRequestId, httpRequest.getHeader(xRequestId))
        chain?.doFilter(request, response)
    }

    override fun destroy() = MDC.remove(xRequestId)
}

控制器:

@PostMapping
fun operation(@RequestHeader(value = "X-Request-Id", required = false) xRequestId: String? = null): ResponseEntity<Output> {
    ....
}

logback.xml

<Pattern>%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level [X-Request-Id: %X{X-Request-Id}] %logger{36}.%M:%line - %msg%n</Pattern>
于 2021-02-09T09:06:57.387 回答