2012-01-17 45 views
1

我有一個被定義爲方法記錄方法...對拋出的異常

公共靜態無效myMethod的拋出IOException異常....

我如何使用Logger類的日誌引發的異常到一個名爲「test.log」的文件。我聽說過使用logger.throwing ...但它似乎不工作。任何人都可以給我一步一步的提示如何做到這一點?我只是基本上需要記錄拋出的異常(我沒有使用try catch)。非常感謝!

+0

你在哪裏要登錄?到控制檯?一份文件?數據庫? – Yogu 2012-01-17 17:40:28

+3

你打算如何記錄異常而不捕捉任何地方? – 2012-01-17 17:42:08

+0

我想登錄到名爲「test.log」的文件。 – user941401 2012-01-17 18:53:50

回答

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(); 
    } 
} 

比較困難的部分是配置記錄器寫在那裏你想要的。 IIRC,默認情況下它會發生標準錯誤。那裏有很多「魔術」,我從來沒有完全理解,所以我無法解釋所有的錯綜複雜。

你可以谷歌獲取信息,這裏有一些我發現的有用的鏈接。 link1link2

+0

不應該在您的示例中重新拋出異常嗎? – 2012-01-17 20:10:14

+0

@daniel kullmann好的,趕上!將修改...並且我接受了您的編輯。 – user949300 2012-01-17 20:12:42

0

嘗試使用jcabi-aspects及其@LogException註釋:

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