Add Timestamp to Trace.WriteLine()

前端 未结 6 939
甜味超标
甜味超标 2021-01-03 20:37

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 Tra

相关标签:
6条回答
  • 2021-01-03 21:15

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-03 21:17

    You can set the app.config file to use a timestamp (relative and current time) for all trace listeners using the traceOutputOptions

    traceOutputOptions = "DateTime, Timestamp";
    
    0 讨论(0)
  • 2021-01-03 21:20

    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);}
    
    0 讨论(0)
  • 2021-01-03 21:28

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

    0 讨论(0)
  • 2021-01-03 21:32

    Via code

    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.

    Via app.config

    This can also be configured in your App.config with a somewhat equivalent and using TraceSource:

    <configuration>
      <system.diagnostics>
        <trace autoflush="true">
          <sources>
            <source name="TraceSourceApp">
              <listeners>
                <add name="myListener" type="System.Diagnostics.ConsoleTraceListener" traceOutputOptions="Timestamp" />
              </listeners>
            </source>
          </sources>
        </trace>
      </system.diagnostics>
    </configuration>
    

    And in code you can:

    private static TraceSource mySource =   
            new TraceSource("TraceSourceApp");
    static void Main(string[] args)
    {
      mySource.TraceInformation("hello world");
    }
    
    0 讨论(0)
  • 2021-01-03 21:38

    You could write your own TextWriterTraceListener, as mentioned here.

    0 讨论(0)
提交回复
热议问题