SpringBoot:如何通过所有程序从控制器传递参数(请求ID)?

时间:2017-12-08 14:34:57

标签: java spring-boot logging slf4j

我使用的是SpringBoot应用。每个请求都有ID。当在某些服务和程序的更低级别的位置记录错误时,我必须使用此ID。我该如何实现它?谢谢!

2 个答案:

答案 0 :(得分:0)

要向您添加上下文ID,您可以使用MDC:

你的代码中的

->with(['relation' => function ($q) {
    $q->with('nestedRelation');
}])
在你的logback.xml中

 MDC.put("first", "Dorothy");

请参阅https://logback.qos.ch/manual/mdc.html

答案 1 :(得分:0)

您可以使用ThreadLocal存储特定线程的ID。

然后,在您的服务中,您可以通过方法ThreadLocal#get获取该ID。

例如(这只是一种方法):

class AppProvider {
    public static final ThreadLocal<String> APP_CONTEXT = new ThreadLocal<String>();
}

class Controller {
    public void users(@RequestParam String id) {
        AppProvider.APP_CONTEXT.set(id);
        .......
    }
}

class Service {
    try {
    } catch (Exception e) {
        log.error(String.format("Id: %s", AppProvider.APP_CONTEXT.get()));
    }
}

这只是一种使用ThreadLocal的方法。

查看此内存泄漏处理: https://stackoverflow.com/a/17975255/1715121