自定义SLF4J记录器 [英] Customize SLF4J Logger

查看:1298
本文介绍了自定义SLF4J记录器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种不错的方式来在我的日志中添加一个前缀,而不必在每次调用时都传递它,而又不会再次使Logger实例化.

I'm trying to find a nice way to add a prefix to my logs without passing it on every calls, without instanciate Logger again.

目的是分别跟踪Rest调用. (前缀将在每次通话时使用UUID重新生成)

The purpose is to trace Rest calls individually. (The prefix would be re-generated on each call using UUID)

这就像

@RestController
class MyClass {
    //Here the prefix is initialise once
    //default value is X
    Logger LOG = LoggerFactory.getLogger(MyClass.class);

    @RequestMapping("/a")
    void methodA() {
        LOG.debug("foo");
    }   

    @RequestMapping("/b")
    void methodB() {    
        LOG.setPrefix("B");

        LOG.debug("bar");
}

具有此输出

[...] [prefix X] foo
[...] [prefix B] bar

推荐答案

正如您所说的那样,您在使用Logback时,可以使用以下两个选项来完成您想做的事情:

As you've said you're using Logback, here's a couple options to do the kind of thing you're trying to do:

每个日志条目都可以为其建立一个标记". (我见过的最好的文档在 SLF4J FAQ 中.)类似:

Each log entry can have a "marker" established for it. (The best documentation I've seen for it is in the SLF4J FAQ.) Something like:

class MyClass {
    Marker methodBMarker = MarkerFactory.getMarker("B");
    Logger logger = LoggerFactory.getLogger(MyClass.class);
    …
    void methodB() {    
        logger.debug(methodBMarker, "bar");
    }
}

您将需要更新每种方法中的所有日志条目以使用适当的标记.然后,您可以在布局中放入 %marker ,以将日志条目的标记放入日志.

You would need to update all log entries in each method to use the appropriate marker. You can then put %marker in your layout to put the log entry's marker into the log.

另一种选择是使用"映射的诊断上下文功能来指定每个日志条目的当前上下文".

The other option is to use the "Mapped Diagnostic Context" functionality to specify the current "context" for each log entry.

class MyClass {
    Logger logger = LoggerFactory.getLogger(MyClass.class);
    …
    void methodB() {
        MDC.put("method", "b");
        try {
            …
            logger.debug("bar");
            …
        } finally {
            MDC.clear();
        }
    }
}

然后,您将在布局中使用 %mdc{method} 来输出特定的MDC值.请注意,MDC实际上是用于每个线程值的,例如特定于Web连接的消息,因此确保在离开要记录值的上下文时清除它是不需要的,这一点很重要.内.

You would then use %mdc{method} in your layout to output that particular MDC value. Note that MDC is really intended to be used for per-thread values like something web-connection-specific, so it's important to ensure that it's cleared out of what you don't want when you're leaving the context you want the value logged in.

这篇关于自定义SLF4J记录器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆