4

I have an instance of a class that lives for a very long time (hours to months). It has a method that outputs log events to a text file C:\mylog.txt. As below

public MyClass
{
    private static System.Diagnostics.TraceSource traceSource = new System.Diagnostics.TraceSource("My.Source");

    private static void MyMethod()
    {
        traceSource.TraceEvent(System.Diagnostics.TraceEventType.Information, 0, "MyMethod called.");
    }
}

This C:\mylog.txt can get quite large and I would like to delete it. But I cannot delete the file presumably because it is locked by the traceSource (by terminating the process I can delete the file).

All examples for the System.Diagnostics.TraceSource declare its instance as a static class member as above. Given my situation, would it be acceptable to initialize it in the method as below?

public MyClass
{
    private static void MyMethod()
    {
        var traceSource = new System.Diagnostics.TraceSource("My.Source");
        traceSource.TraceEvent(System.Diagnostics.TraceEventType.Information, 0, "MyMethod called.");
    }
}

Or is there a specific reason why it must be declared static? Am I doing something wrong? Is the file locking expected/required behavior?

shA.t
  • 16,580
  • 5
  • 54
  • 111
Kevin Brydon
  • 12,524
  • 8
  • 46
  • 76

1 Answers1

6

You are looking at the wrong side of the railroad track for this problem. The TraceSource does not determine how trace data is recorded. That is done by another class in .NET, the TraceListener. The division between the two is important, the trace source is just an interesting source of tracing information, the listener determines exactly how it is filtered for less important info and how it is recorded.

There's no insight from the question how you configured the listener. Using the .config file is a common way.

You need a different kind of listener. A very simple one would open the log file when a trace event needs to be recorded and close it again immediately after writing the string. Which gives you a shot at deleting the file, albeit that you have to still do it at exactly the right time. That is however not the Right Way, it is very inefficient.

A common solution is a "rolling appender", a listener that records log info into a file but ensures it doesn't get too big. Then switches to another file and deletes very old ones so you don't get too many of them. Not the kind of code you'd want to write yourself, it is readily available from a library. The kind you can get through Nuget. I'd recommend NLog, based on the popular Apache Log4Net library but made more .NET centric. This question covers it.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536