46

自定义一个logback的MessageConverter

 4 years ago
source link: https://www.hollischuang.com/archives/3689?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

我们在开发的时候,经常要打印日志,有的时候会在一些代码的关键节点处进行日志输出。

使用logback/log4j等原生的日志框架,在日志输出的时候可能会遇到一个问题,那就是在打印对象的时候要求对象必须重写toString方法,否则无法将该对象的参数打印出来。

如代码 : log.info("req = {}", creditApplyRequest);

日志输出:

req = com.xxx.yyy.core.functions.credit.request.CreditApplyRequest@39ddf169

我们一般要求对于自己定义的入参、出参等定义toString方法。

但是有些时候,我们使用的是外部定义的request和response对象,他们并没有覆盖toString,当对这些对象打印的时候,就会出现以上问题。

一般简单的解决办法是,可以通过JSON把对象转成String,如:

代码 : log.info("req = {}", JSON.toJSONString(ScreditApplyRequest));

日志输出:

req = {"creditInstitution":"","creditRole":"SELLER","customer":{"aliId":,"customerId":"","customerType":"ALI"},"origin":"PC","productType":"","tenant":""}

但是,这样的话,就需要在日志记录的地方人为的要处理下,很不高效。有一个好的办法,可以一劳永逸:

借助logback(log4j也有类似的功能)的MessageConverter。无侵入性的解决这个问题

1、自定义一个Layout

/**
 * 参数JSON格式化类
 *
 * @author Hollis
 */
public class ArgumentJsonFormatLayout extends MessageConverter {

    @Override
    public String convert(ILoggingEvent event) {
        try {
            return MessageFormatter.arrayFormat(event.getMessage(), Stream.of(event.getArgumentArray())
                .map(JSON::toJSONString).toArray()).getMessage();
        } catch (Exception e) {
            return event.getMessage();
        }
    }
}

2、在logback中配置上这个Layout

<configuration>
    <conversionRule conversionWord="m" converterClass="com.xxx.yyy.zzz.ArgumentJsonFormatLayout"/>
 </configuration>

这样,就可以直接使用 log.info("req = {}",obj) 这样的形式记录日志了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK