views:

1331

answers:

5

In my C# .NET application I have an issue with the Trace.WriteLine()-method. I uses this method alot, and want to add a TimeStamp every time I use it.

Instead of Trace.WriteLine(DateTime.Now + " Something wrong!"), is there a solution where the DateTime is on default?

A: 

You could write a wrapper method that did it:

public static void DoTrace(string message)
{
    DoTrace(message,true);
}

public static void DoTrace(string message, bool includeDate)
{
    if (includeDate) {
        Trace.WriteLine(DateTime.Now + ": " + message);
    } else {
        Trace.WriteLine(message);
    }
}
Lloyd
This wouldn't work because DoTrace is static and you don't have access to Trace. You could use HttpContext.Current.Trace.WriteLine(DateTime.Now + ": " + message)
Darin Dimitrov
Isn't System.Diagnostics.Trace.WriteLine() also static? Depends which he's using I guess :/
Lloyd
+1  A: 

Just write your own "TraceLine(string msg)" method and start calling that:

void TraceLine(string msg, bool OmitDate)
{
    if (!OmitDate)
        msg = DateTime.Now + " " + msg;
    Trace.WriteLine(msg);
}

void TraceLine(string msg) {TraceLine(msg, false);}
Joel Coehoorn
These should be static methods, as no dependency on the object calling them.
JDunkerley
I'd suggest logging with UTC timestamps to avoid any ambiguity in timezones etc. - also you might want to use Format or StringBuilder to avoid all those temporary strings
morechilli
actually, the most efficient string concatenation method is probably string.Concat(). Not that it would matter anyway.
DonkeyMaster
A: 

We use log4net TraceAppender where you can config layout or filtering easily.

Kai Wang
A: 

I thought actually, there was a way of override the method Trace.WriteLine(), like when you override ToString()?

+3  A: 

You can configure the TraceOutputOptions flags enum.

var listener = new ConsoleTraceListener() { TraceOutputOptions = TraceOptions.Timestamp | TraceOptions.Callstack };
Trace.Listeners.Add(listener);

Trace.TraceInformation("hello world");

This does not work for Write and WriteLine, you have use the TraceXXX methods. This can also be configured in your App.config.