Simple way to perform error logging?

I wouldn’t dig too much on external libraries since your logging needs are simple.

.NET Framework already ships with this feature in the namespace System.Diagnostics, you could write all the logging you need there by simply calling methods under the Trace class:

Trace.TraceInformation("Your Information");
Trace.TraceError("Your Error");
Trace.TraceWarning("Your Warning");

And then configure all the trace listeners that fit your needs on your app.config file:

<configuration>
  // other config
  <system.diagnostics>
    <trace autoflush="true" indentsize="4">
      <listeners>
        <add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>
        <add name="textWriterListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="YourLogFile.txt"/>
        <add name="eventLogListener" type="System.Diagnostics.EventLogTraceListener" initializeData="YourEventLogSource" />
        <remove name="Default"/>
      </listeners>
    </trace>
  </system.diagnostics>
  // other config
</configuration>

or if you prefer, you can also configure your listeners in your application, without depending on a config file:

Trace.Listeners.Add(new TextWriterTraceListener("MyTextFile.log"));

Remember to set the Trace.AutoFlush property to true, for the Text log to work properly.

Leave a Comment