C# : Trace the log messages

This example says how to Trace the log messages in C#.

The namespaces required:
using System;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.Configuration;

[DebuggerHidden]
[Conditional( "TRACE" )]
static public void TraceWrite(
string userName,
string messageFormat,
params string[] args )
{
// get the first method that does not have
            // the same declaring type of the declaring type
            // of this method
            MethodBase mb_this = MethodBase.GetCurrentMethod();
            Type t_this = mb_this.DeclaringType;
             int sf_offset = 1;
MethodBase mb_caller;
StackFrame sf;
do
            {
                sf = new StackFrame( sf_offset );
mb_caller = sf.GetMethod();
++sf_offset;
}
while ( mb_caller.DeclaringType == mb_this.DeclaringType );

string msg = string.Format( CultureInfo.CurrentCulture,
"{0:yyyy/MM/dd HH:mm:ss},{1},{2}.{3},\"{4}\"",
DateTime.Now,
userName,
mb_caller.DeclaringType,
mb_caller.Name,
string.Format( CultureInfo.CurrentCulture,
messageFormat, args ) );

Trace.WriteLine( msg );
}
By Perry    Popularity  (4397 Views)