다음을 통해 공유


C#: Creating a Simple Logging class with System.Diagnostics Namespace

Here in this post, I am going to show how to configure and create a Logger class using System.Diagnostics namespace in C#.

Classes from the System.Diagnostics names, explained.

TraceListener
TraceListener class is used to perform the IO operation. That is, writing the textual data to the log file.


**BooleanSwitch
**BooleanSwitch class is used to enable / disable the logging entirely, based on the application's configuration setting.


**TraceSwitch
**TraceSwitch class is used to decide what type of data has to be logged into the log file. 4 different types can be handled by this TraceSwitch.

Switch Types  Configuration Values   Description
 Error  1 Log only the errors
 Warning  2 Log only the warnings
 Information  3 Log only the information
 Verbose  4 Log all the above 

Application Configuration Settings

01.<configuration>
02.  <appSettings>
03.    <!--  
04.      Log 
05.      ============================================================
06.      1 - Enable Logging
07.      0 - Disable Logging
08.      ============================================================
09.    -->
10.    <add key="Enable" value="1" />
11.    <!--
12.      Log Type 
13.      ============================================================
14.      1 - Errors
15.      2 - Warnings
16.      3 - Information
17.      4 - Verbose - All errors, warning and info will be logged.
18.      ============================================================
19.    -->
20.    <add key="Type" value="1" />
21.   </appSettings>
22.   <system.diagnostics>
23.    <trace autoflush="true">
24.      <listeners>
25.        <clear />
26.        <add name="Tracer" initializeData="app.log"
27.                 type="System.Diagnostics.TextWriterTraceListener"
28.                 traceOutputOptions="Timestamp" />
29.      </listeners>
30.    </trace>
31.  </system.diagnostics>
32.</configuration>

Creating the Logging class with appropriate method for each type (Error, Info, Warn)

01.public class  MyLog
02.{
03.    TraceListener tListener = null;
04.    BooleanSwitch bSwitch = null;
05.    TraceSwitch   tSwitch = null;
06.         
07.    public MyLog()
08.    {
09.        //Create the listener based on the configuration setting
10.        tListener = Trace.Listeners["Tracer"];
11.        //Create the boolean and trace switch based on the configuration settings
12.        bSwitch = new  BooleanSwitch("Enable", "", ConfigurationManager.AppSettings["Enable"]);
13.        tSwitch = new  TraceSwitch("Type", "", ConfigurationManager.AppSettings["Type"]);
14.    }
15. 
16.    public void  Error(string  messageToLog)
17.    {
18.        if (bSwitch.Enabled && (tSwitch.TraceError || tSwitch.TraceVerbose))
19.        {
20.            tListener.WriteLine(messageToLog);
21.        }
22.    }
23. 
24.    public void  Warn(string  messageToLog)
25.    {
26.        if (bSwitch.Enabled && (tSwitch.TraceWarning || tSwitch.TraceVerbose))
27.        {
28.            tListener.WriteLine(messageToLog);
29.        }
30.    }
31. 
32.    public void  Info(string  messageToLog)
33.    {
34.        if (bSwitch.Enabled && (tSwitch.TraceInfo || tSwitch.TraceVerbose))
35.        {
36.            tListener.WriteLine(messageToLog);
37.        }
38.    }
39.}

Now we can use MyLog class and three methods to enable the logging operations in an application. Method can be customized to add more information in the log like Method Name, Exception messages with stack trace and inner exception details.

Feel free to share your thoughts and comments about this post. If there is any improvisation can be done to above given sample code, please let me know.

Thanks.