Write to same log file two instances of the same application

969 Views Asked by At

How write to same file from two instance of the same application. For write I used TraceSource class with TraceEvent method from System.Diagnostis namespace. I try create method with Mutex for write, but my method don't work correctly. I can't find example for TraceSource logging with mutex. Can anybody help me?

My Log class:

public class LoggerTraceSource
 {
   private readonly TraceSource traceSource = new TraceSource();

  public void InfoTraceEvent(string message, int level)
        {
            traceSource.TraceEvent(TraceEventType.Information, level, message);
        }
 }

In my application I used InfoTraceEvent for write to log file. How change InfoTraceEvent for threading write(write by two application instance)?

1

There are 1 best solutions below

0
On

I'm doing some ESP diagnostics here because I don't know what the symptoms are. I'm guessing you have process1.exe and process2.exe each with identical system.diagnostics sections, i.e. writing to the same file.

As soon as process1.exe starts writing to the trace file, it holds a lock for the duration of the process. When process2.exe tries to write to the same file, it will machine generate a name for a new file, like file13.txt

This behavior can vary depending on the listener. For example, if you write a custom listener that blocks on attempts to write to a locked file, then you'd see that behavior.

I'd recommend either writing to 2 different files or using a custom listener that closes the file handle after each write. This would require doing re-tries when the two processes happen to try to open the file simultaneously.