簡體   English   中英

為JUnit配置log4j

[英]Configuring log4j for JUnit

我想為JUnit測試案例配置log4j。 我的測試分散在多個文件中,但是具有相同的log4j設置。 我在哪里可以做?

我不想使用log4j屬性文件。

我的解決方案,似乎可行。

編寫一個擴展Log4j系統的自定義類

公共類myLogger擴展了Logger {...東西...

}

對於“東西”,您需要實現以下內容(或者至少我做到了)

某種公共myLogger的構造函數(字符串名稱)

..在每個類中,您想要/需要包含myLogger的靜態成員的位置

private static final myLogger errorLog =  new myLogger("nameOfClassOrWhateverNameYouFancy")

如果您在所有類中使用相同的名稱,則它們將記錄到相同的記錄實例(您可能已經知道)

回到您的myLogger類中,您需要實現一種用於設置日志級別的方法(這就是我的方法...)

/**
 * 
 * The add(int i, String s) method
 * @param s the message string
 *
 * @param i used in the switch to create the required level of debug
 * @param s the message to send
 * 
 * use this method to create a log message of any required level
 * The levels are as follows:
 * 1    debug - used during production
 * 2    info  - may be used for messages to user
 * 3    warn  - warnings for requesting users re-enter information (data type checking etc)
 * 4    error - programmatic / user error may result in unexpected output 
 * 5    fatal - severe error (comms error) the system will terminate, cleanly if possible, current state will be written to file
 * 
 * Prior to all this however the method determines the calling class of itself
 * 
 */

public void add(int i, String s)
{




    switch (i)
    {
    case 1: log.debug(s);break;
    case 2: log.info(s);break;
    case 3: log.warn(s);break;
    case 4: log.error(s);break;
    case 5: log.fatal(s);break;
    }
}

現在,如果您想為“奇怪的東西”提供一些特定的日志記錄實例,則有兩個選擇,就像我之前說的那樣,您可以為命名記錄器創建一個靜態成員,或者可以將靜態成員添加到myLogger類(這就是我的方式)。做到了)。

那么對於這些​​靜態成員中的每一個,您可能想要一個唯一的

set[nameOfLogger](int i, string s)

基本上具有與上述方法相同的結構。

現在,如果您想從班級中調用它

myLogger.set[nameOfLogger](1, "s")

而你不在。

然后,您需要將有關日志級別(調試,警告等)以及將消息發送到何處(控制台,文件等)的信息添加到您的log4j.properties(如我所用)或log4j.xml中。

請記住,要確保有關設置靜態命名記錄器的行出現在rootLogger實例之后,這使我困擾了很長時間!

我花了很長時間才把我認為是相當廣泛的說明包括在內,直到今天才完成工作!

我現在是一個快樂的兔子。。。。

大衛

抱歉,您剛剛發現您不想使用log4j.properties文件。 特別是什么原因?

如果不是

import org.apache.log4j.Logger;

創建一個日志記錄實例

private Logger jUnitTestingLogger;

然后使用各種方法調用設置輸出(我特別考慮添加追加器),我從來沒有像這樣做過,所以不知道怎么做!

有趣的是,有一個assertLog(boolean assertion,string message)方法可能對您的實例有利。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM