本文介绍了如何创建MyLogger?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用log4j进行日志记录。我想修改方法:warn(..),error(..)。我想在这个方法中修改消息。
那么,有什么办法,如何创建我自己的记录器?

I use log4j for logging. And I would like to modify methods: warn(..), error(..). I would like to modify message in this methods.So, is there any way, how to create my own logger?

public class MyLogger extends Logger {

protected MyLogger(String name) {
    super(name);
}

@Override
public void error(Object message) {
    message = "test - " + message;

    super.error(message);
}

}

在课堂电话中:

private static final Logger logger = MyLogger.getLogger(TestClass.class);

logger.error("error message");

但是,它不起作用。你可以帮帮我吗?谢谢。

But it, do not work. Could you help me? Thanks.

推荐答案

你的问题是:

MyLogger.getLogger(TestClass.class)

static 返回原始 Logger 类的方法。忽略 MyLogger 。最简单的方法是以模式:

is a static method which returns original Logger class. MyLogger is ignored. The easiest approach is to wrap originally returned Logger class in the spirit of decorator pattern:

public class MyLogger extends Logger {
    final Logger target;
    protected MyLogger(Logger target) {
        this.target = target;
    }

    @Override
    public void error(Object message) {
        target.error(message);
    }

    //...

}

为了使用 MyLogger 装饰器,你必须用它包装原始记录器:

In order to use MyLogger decorator you must wrap original logger with it:

private static final Logger logger = 
  new MyLogger(Logger.getLogger(TestClass.class));

考虑将其包装在自定义工厂中。

Consider wrapping it in custom factory.

这篇关于如何创建MyLogger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 07:18