Simple way to perform error logging?

Analytic Lunatic picture Analytic Lunatic · Dec 11, 2013 · Viewed 101.4k times · Source

I've created a small C# winforms application, as an added feature I was considering adding some form of error logging into it. Anyone have any suggestions for good ways to go about this? This is a feature I've never looked into adding to previous projects, so I'm open to suggestions from Developers who have more experience.

I was considering something along the lines of writing exceptions to a specified text file, or possibly a database table. This is an application that will be in use for a few months and then discarded when a larger product is finished.

Answer

Mauro2 picture Mauro2 · Dec 11, 2013

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.