Search code examples
fileloggingpostsharp

write log to file instead of console in postsharp


I know this question may be ridiculous but I could not find the answer. The Post sharp writes the logs in console by System.Diagnostics but I need to write the logs in a separate file. Is there any way to do so?

Thanks in advance


Solution

  • You need to use System.Diagnostics.Trace.Listeners property to register your own listener. You would need code like this in your app's entry point:

    using (StreamWriter sw = new StreamWriter("file.txt"))
    using (TextWriterTraceListener tl = new TextWriterTraceListener(sw))
    {
        Trace.Listeners.Add(tl);
    
        try
        {
            // execute your program here
        }
        finally
        {
            Trace.Listeners.Remove(tl);
        }
    }