Formatting trace output

前端 未结 7 970
南笙
南笙 2020-12-29 09:14

I\'m using TextWriterTraceListener to log diagnostics messages to a text file. However I wan\'t also to log a timestamp of every trace message added. Is it poss

相关标签:
7条回答
  • 2020-12-29 09:35

    Or just add "DateTime" as a traceOutputOption.

    0 讨论(0)
  • 2020-12-29 09:41

    You could write your own TextWriterTraceListener subclass which overrides the WriteLine methods, decorates the line, and then passes the decorated string to the base class implementation to do the actual output.

    0 讨论(0)
  • 2020-12-29 09:41

    Consider using The Logging Application Block

    0 讨论(0)
  • 2020-12-29 09:45

    I suggest you use Log4Net instead, which has a lot more customizability.

    Alternatively you could write your own TraceListener implementation which put the timestamps on for you. You may even be able just derive from TextWriterTraceListener and override Write and WriteLine:

    public override void Write(string x)
    {
         // Use whatever format you want here...
         base.Write(string.Format("{0:r}: {1}", DateTime.UtcNow, x));
    }
    
    public override void WriteLine(string x)
    {
         // Use whatever format you want here...
         base.WriteLine(string.Format("{0:r}: {1}", DateTime.UtcNow, x));
    }
    

    As noted in comments, this ends up with date duplication for TraceInformation, because that calls Write twice. Using a "proper" logging framework is definitely better.

    0 讨论(0)
  • 2020-12-29 09:45

    Not really an answer to your question but have you considered just using log4Net?

    You can configure it to add times etc, along with a vast amount of other useful functionality.

    0 讨论(0)
  • 2020-12-29 09:47

    I recently encountered similar situation and it looks like now we have a tool very much fit for the task, namely Essential Diagnostics. You set up a listener in app.config like in code below and then just place Essential.Diagnostics.dll into the same folder. NO RECOMPILING IS REQUIRED. You can use this with any applications that uses System.Diagnostics for tracing, even if you do not own the source. Isn't that marvelous?

    <sharedListeners>
      <add name="rollingfile"
        type="Essential.Diagnostics.RollingFileTraceListener, Essential.Diagnostics"
        initializeData="{ApplicationName}-{DateTime:yyyy-MM-dd}.log"
        convertWriteToEvent="true" 
        template="{DateTime:yyyy-MM-dd HH:mm:ss.fff} {Message}{Data}"
      />
    </sharedListeners>
    
    0 讨论(0)
提交回复
热议问题