can't write into log file using TraceSource Method in C#

守給你的承諾、 提交于 2020-01-02 11:21:12

问题


I am using the following code to log the exception, but it's not writing any logs into the file "mylistener.log". What am I missing here?

using System;
using System.Diagnostics; 

namespace TraceSourceApp
{
    class Program
    {
        private static TraceSource mySource = new TraceSource("TraceSourceApp");
        static void Main(string[] args)
        {          
            TextWriterTraceListener textListener = 
               new TextWriterTraceListener("myListener.log");

            mySource.Listeners.Add(textListener);
            int i = 10, j = 0, k;
            try
            {
                k = i / j;
            }
            catch
            {
                mySource.TraceEvent(TraceEventType.Error, 12,
                    "Division by Zero");
            }      
            mySource.Close();               
        }           
    }
}

回答1:


In order for the TraceSource to write data to the file, you need to set the Switch-property of the TraceSource to a SourceSwitch instance. Change your code as follows:

static void Main(string[] args)
{
    TextWriterTraceListener textListener = new TextWriterTraceListener("myListener.log");
    // New code starts here
    var sourceSwitch =  new SourceSwitch("SourceSwitch", "Verbose");
    mySource.Switch = sourceSwitch;
    // New code ends here
    mySource.Listeners.Add(textListener);
    // ...

In addition to have the TraceWriter flush its content automatically, set Trace.AutoFlush at the beginning of you main method (the sample works without it, but it is always a good idea to make sure that the listeners are flushed in order not to loose log entries):

static void Main(string[] args)
{
    Trace.AutoFlush = true;
    // ...

As an alternative, you can also flush the listener explicitly by calling its Flush-method at the end:

textListener.Flush();
mySource.Close();

In real world code, I'd suggest to add a try-finally or using block to assert that Flush is called and that the source is closed.



来源:https://stackoverflow.com/questions/21347295/cant-write-into-log-file-using-tracesource-method-in-c-sharp

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