我有一個被定義爲方法記錄方法...對拋出的異常
公共靜態無效myMethod的拋出IOException異常....
我如何使用Logger類的日誌引發的異常到一個名爲「test.log」的文件。我聽說過使用logger.throwing ...但它似乎不工作。任何人都可以給我一步一步的提示如何做到這一點?我只是基本上需要記錄拋出的異常(我沒有使用try catch)。非常感謝!
我有一個被定義爲方法記錄方法...對拋出的異常
公共靜態無效myMethod的拋出IOException異常....
我如何使用Logger類的日誌引發的異常到一個名爲「test.log」的文件。我聽說過使用logger.throwing ...但它似乎不工作。任何人都可以給我一步一步的提示如何做到這一點?我只是基本上需要記錄拋出的異常(我沒有使用try catch)。非常感謝!
您需要添加一個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();
}
}
比較困難的部分是配置記錄器寫在那裏你想要的。 IIRC,默認情況下它會發生標準錯誤。那裏有很多「魔術」,我從來沒有完全理解,所以我無法解釋所有的錯綜複雜。
不應該在您的示例中重新拋出異常嗎? – 2012-01-17 20:10:14
@daniel kullmann好的,趕上!將修改...並且我接受了您的編輯。 – user949300 2012-01-17 20:12:42
如果你想比user949300給出一個更自動化的方法,你可以看看面向方面編程(AOP),它允許你用的只是一點點的所有方法做異常記錄的代碼。只需谷歌aspectj log exceptions或java aop log exceptions。
參見問題Audit Java: system to detect exceptions thrown/caught (aop?)
嘗試使用jcabi-aspects及其@LogException
註釋:
public class Resource {
@LogExceptions
public String load(URL url) {
return url.openConnection().getContent();
}
}
你在哪裏要登錄?到控制檯?一份文件?數據庫? – Yogu 2012-01-17 17:40:28
你打算如何記錄異常而不捕捉任何地方? – 2012-01-17 17:42:08
我想登錄到名爲「test.log」的文件。 – user941401 2012-01-17 18:53:50