Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms logging framework

Tags:

c#

.net

logging

I'm writing a WinForms application. I need to log information into a file. Usually I use log4net for logging, but I cannot add the reference, due to a restriction. I cannot add external references to my project, because I must deploy a single executable.

Is there any built-in logging framework in .NET so I will be able to log into a file without adding an external dll?

P.S: Of course I don't wanna open a stream and write manually.

like image 655
Daniel Peñalba Avatar asked Jul 10 '12 08:07

Daniel Peñalba


2 Answers

Yes, the System.Diagnostics.TraceListener class. You will need to define the TRACE constant for it to work, but you can use a number of built in tracelisteners, through configuration of your app.config:

  • ConsoleTraceListener Class
  • EventLogTraceListener Class
  • XmlWriterTraceListener Class
  • TextWriterTraceListener Class

The app.config looks something like this if you want to write to a file, there are a lot of filters you can also add:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.diagnostics>
        <trace autoflush="false" indentsize="4">
          <listeners>
            <add name="yourName" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\mylogfile.txt" />
          </listeners>
        </trace>
    </system.diagnostics>
</configuration>

And usage:

Trace.TraceError("There's been an error captain: {0}", e);
Trace.TraceWarning("The system broke but don't worry.");
Trace.TraceInformation("Starting up the engines.");

Personally I wouldn't write to a text file if you can avoid it, the Event Log is a better location as you can sort, filter, the logs are auto-purged and you don't get file lock up issues.

like image 123
Chris S Avatar answered Sep 28 '22 05:09

Chris S


Well, if you're comfortable with log4net so be it. Use the logging tool of your choice, and in post-build use ILMerge to merge all dependencies into a single executable.

This is exactly the scenario that it is intended for.

There's also a GUI for it, if you don't want to use it in command line mode.

like image 25
Asti Avatar answered Sep 28 '22 06:09

Asti