How do you stop a TextWriterTraceListener from appending using app.config?

三世轮回 提交于 2020-01-14 10:09:04

问题


I'm using System.Diagnostics.TraceSource for logging and one of my listeners is a TextWriterTraceListener. In the tracing primer here it sets this up as follows:

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

The problem is that this will always append to output.txt. How do you alter this to an overwrite in the config file?

Programmatically the listener I want is a:

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

回答1:


The simplest solution is to make your own.

I suggest that you inherit from TextWriterTraceListener and in your constructor set the base Writer to what you proposed: new StreamWriter("output.txt", false).

Some sample code:

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

This lets you take the initializeData parameter from a configuration file to specify the name of the file, or specify one if created in code.




回答2:


I know this doesn't directly answer your question, but use NLog instead. It does more stuff than out-of-the-box diagnostics in terms of logging options and it's really easy to use.




回答3:


Even more simpler, just tell the TestWriterTraceListener to not append the file:

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

By selecting false the logfile is overwritten each time you initialize the TextWriterTraceListener.



来源:https://stackoverflow.com/questions/9171376/how-do-you-stop-a-textwritertracelistener-from-appending-using-app-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!