2012-02-07 46 views
5

我使用System.Diagnostics.TraceSource進行日誌記錄,我的一個偵聽器是TextWriterTraceListener。在跟蹤底漆here它設置這件事如下:如何阻止TextWriterTraceListener使用app.config追加?

<listeners> 
    <add initializeData="output.txt" 
     type="System.Diagnostics.TextWriterTraceListener" 
     name="myLocalListener" /> 
</listeners> 

的問題是,這將始終添加到output.txt。你如何改變這個配置文件覆蓋?

編程我想聽衆是:

new TextWriterTraceListener(new StreamWriter("output.txt", false)); 

回答

2

最簡單的解決方案就是製作你自己的。

我建議你繼承TextWriterTraceListener,並在你的構造函數中設置基地Writer爲你所建議的:new StreamWriter("output.txt", false)

一些示例代碼:

public class MyTextWriterTraceListener : TextWriterTraceListener 
{ 
    public MyTextWriterTraceListener(string logFileName) 
     : base(logFileName) 
    { 
     base.Writer = new StreamWriter(logFileName, false); 
    } 
} 

這可以讓你把initializeData參數從配置文件中指定的文件名,或者如果在代碼中創建指定一個。

+0

我喜歡這個想法,但是當在App.config中輸入type = MyNamespace.MyTextWriterTraceListener時,程序崩潰。 – 2014-03-06 22:36:25

+0

有趣。我前幾天做了一個類似的自定義監聽器,沒有任何問題。我必須添加到我的app.config中的一點是'type =「MyNamespace.MyTextWriterTraceListener,AssemblyNameContainingListener」'。還要確保包含它的程序集正在被複制,我有一個單元測試,它在app.config中引用它,但在代碼中沒有引用,所以Visual Studio有足夠的幫助,不會將其複製到本地。 – 2014-03-07 16:25:45

+0

謝謝,我正在離開程序集名稱。 – 2014-03-10 02:53:18

1

我知道這並不直接回答你的問題,但使用NLog代替。它在日誌記錄選項方面比現成的診斷功能做得更多,而且它非常易於使用。

+3

-1根本不回答問題。 OP沒有要求替代日誌解決方案,而是如何配置所選的日誌解決方案。 – 2014-03-06 17:42:14

+1

@JonPeterson我不同意。有一個合理的機會,這個答案對別人有幫助。 – Holf 2016-12-22 12:42:14

0

更簡單,只是告訴TestWriterTraceListener不追加文件:

TextWriterTraceListener twtl = new TextWriterTraceListener(new StreamWriter(@"<path to my logfile>", false)); 

通過選擇false日誌文件每次初始化TextWriterTraceListener會時被覆蓋。

+0

謝謝,但我一直在尋找一種解決方案,允許在配置中指定編寫器。你的解決方案在問題的底部,因爲我想複製的行爲:) – 2014-10-23 09:38:29