如何使用logger打印异常? [英] how to print an exception using logger?

查看:803
本文介绍了如何使用logger打印异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我想使用记录器打印catch块中捕获的所有异常。

I have a situation in which I want to print all the exception caught in catch block using logger.

 try {
        File file = new File("C:\\className").mkdir();
        fh = new FileHandler("C:\\className\\className.log");
        logger.addHandler(fh);
        logger.setUseParentHandlers(false);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
    } catch (Exception e) {
        logger.info(e);
    }

我得到的错误记录器无法应用于 java .io.Exception ...

i got the error logger cannot be applied to java.io.Exception...

我关心的是如果我在try块中做了很多事情而且我只保留了一个catch块作为catch (例外e),那么有没有办法使用记录器来打印catch块中捕获的任何异常?
注意:我们正在使用java.util.logging.Logger API

My concern is if I do so many thing in try block and I keep only one catch block as catch(Exception e), Then is there any way using logger that print any kind of exception caught in catch block ? Note: we are using java.util.logging.Logger API

推荐答案

你应该澄清你是哪个记录器使用。

You should probably clarify which logger are you using.

org.apache.commons.logging.Log interface has method void error (对象消息,Throwable t)(和方法 void info(对象消息,Throwable t)),它将堆栈跟踪与您的自定义一起记录信息。 Log4J实现也有这个方法。

org.apache.commons.logging.Log interface has method void error(Object message, Throwable t) (and method void info(Object message, Throwable t)), which logs the stack trace together with your custom message. Log4J implementation has this method too.

所以,你可能需要写:

logger.error("BOOM!", e);

如果你需要用INFO级别记录它(不过,它可能是一个奇怪的用例),然后:

If you need to log it with INFO level (though, it might be a strange use case), then:

logger.info("Just a stack trace, nothing to worry about", e);

希望有所帮助。

这篇关于如何使用logger打印异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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