How can I use Logback to log to 2 different files in the same class?

时间:2015-05-12 23:18:38

标签: java slf4j logback

Our Java application uses SLF4J on top of Logback to log error messages. In our logback.xml, we have an laber.asm:1: error: label or instruction expected at the start of line defined for the error log, along with a appender that specifies the top level of our package hierarchy.

We are adding functionality to log data to a different log file. I created a class to handle this logging, and I added a new logger to the logback.xml as well as a new appender. The new logger specifies the fully qualified package name of the new class that I created (along with logger), so that only that specific class will write to the new log file when it invokes the SLF4J logger.

Then I realized that if the new class fails to write to the new log file for whatever reason, I should have it log an error message to our original error log file. But how can that class write to the original error log file, when its SLF4J logger writes to the new log file? Is there a way for that class to get a handle to a logger to the original error log file?

1 个答案:

答案 0 :(得分:-1)

最简单的方法是让新类有两个记录器:一个是它自己的记录器,另一个是用于记录错误的记录器。一个班级不允许同时使用两个记录器(但出于不同目的):

public class NewClass {
    private static final Logger logger = LoggerFactory.getLogger(NewClass.class);
    private static final Logger errorLogger = LoggerFactory.getLogger(ErrorHandlingClass.class);

    public void respond() {
        logger.info("info file");
        try {
            doSomething();
        } catch (Exception e) {
            errorLogger.error("error doing something", e);
        }
    }

然而,如果您写入"新日志文件"使用SLF4J记录器,我认为你无法检测到写入失败。