抛出异常的记录方法

时间:2012-01-17 17:37:34

标签: java exception logging

我的方法定义为......

public static void myMethod抛出IOException ....

如何使用Logger类记录抛出到名为“test.log”的文件的异常。我听说过使用logger.throwing ......但它似乎没有用。谁能给我一步一步的提示如何做到这一点?我只是需要记录抛出的异常(我没有使用try catch)。非常感谢你!

3 个答案:

答案 0 :(得分:2)

您需要添加一个catch子句。下面是使用java.util.logging.Logger的开始。请注意,许多项目使用Apache记录器,它更强大,更复杂。假设您有一个com.myCompany.Foo类,它可以读取一些文件

通常,在静态字段声明中类的开头,您将有

private static final Logger LOGGER = Logger.getLogger("com.myCompany.Foo");

然后,当你有一个抛出异常的方法时(这是一个愚蠢的方法!)

int readFirstCharOfFile(File f) throws IOException {
   FileReader reader = null;
   try {
      reader = new FileReader(f);
      return reader.read();
   }
   catch (IOException ioe) {
      // You have a lot of possibilities here, but this seems most reasonable
      LOGGER.log(Level.SEVERE, ioe.getMessage(), ioe);

      // whether you rethrow the Exception "depends" on the contract, but, in our case
      // the method declaration says that we do, so we do.
      throw ioe;
   }
   finally {
      if (reader != null)
         reader.close();
   }
}

更难的部分是将Logger配置为在您想要的位置写入。 IIRC,默认情况下会出现标准错误。那里有很多“神奇”,我从未完全理解,所以我无法解释所有错综复杂的内容。

你可以谷歌获取信息,这里有一些我发现的有用链接。 link1link2

答案 1 :(得分:0)

如果您想要一种比user949300更自动的方法,您可以看一下面向方面编程(AOP),它允许您只需一点点代码就可以对所有方法进行异常记录。只需谷歌aspectj log exceptionsjava aop log exceptions

另见问题Audit Java: system to detect exceptions thrown / caught (aop?)

答案 2 :(得分:0)

尝试使用jcabi-aspects及其@LogException注释:

public class Resource {
  @LogExceptions
  public String load(URL url) {
    return url.openConnection().getContent();
  }
}
相关问题