C# 格式化跟踪输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1171670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:58:21  来源:igfitidea点击:

Formatting trace output

c#debuggingformattingtracetrace-listener

提问by RaYell

I'm using TextWriterTraceListenerto log diagnostics messages to a text file. However I wan't also to log a timestamp of every trace message added. Is it possible to define a kind of formatter for the listener that would automatically add timestamps?

我正在使用TextWriterTraceListener将诊断消息记录到文本文件中。但是,我也不想记录添加的每个跟踪消息的时间戳。是否可以为侦听器定义一种自动添加时间戳的格式化程序?

Currently I'm adding timestamps manually on every Trace.WriteLine()call but this isn't very comfortable.

目前我在每次Trace.WriteLine()通话时手动添加时间戳,但这不是很舒服。

采纳答案by Jon Skeet

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

我建议您改用Log4Net,它具有更多的可定制性。

Alternatively you could write your own TraceListenerimplementation which put the timestamps on for you. You mayeven be able just derive from TextWriterTraceListenerand override Writeand WriteLine:

或者,您可以编写自己的TraceListener实现,为您添加时间戳。你可能甚至可以从他们只派生TextWriterTraceListener和覆盖WriteWriteLine

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 Writetwice. Using a "proper" logging framework is definitely better.

正如评论中所指出的,这最终导致 的日期重复TraceInformation,因为这会调用Write两次。使用“适当的”日志框架肯定会更好。

回答by Steve Gilham

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.

您可以编写自己的 TextWriterTraceListener 子类,该子类覆盖 WriteLine 方法、装饰行,然后将装饰后的字符串传递给基类实现以执行实际输出。

回答by Russell Troywest

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

不是您问题的真正答案,但您是否考虑过仅使用log4Net

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

您可以将其配置为添加时间等,以及大量其他有用的功能。

回答by Dzmitry Huba

回答by Dzmitry Huba

Or just add "DateTime" as a traceOutputOption.

或者只是添加“DateTime”作为traceOutputOption。

回答by wageoghe

Even though this is old and an answer has been accepted, I will throw in one more option. You can use the Ukadc.Diagnosticsaddon from codeplex. Among other things, it enables you to define custom formatting, similar to the formatting that you can define with log4net and NLog. It is a configuration-only dependency. That is, you configure the use of Ukadc.Diagnostics through the app.config file. There are no source dependencies (you continue to log via System.Diagnostics not through a special api). Having said that, there are some limitations that you should be aware of:

即使这是旧的并且已经接受了答案,我还是会提出一个更多的选择。您可以使用codeplex 中的Ukadc.Diagnostics插件。除此之外,它使您能够定义自定义格式,类似于您可以使用 log4net 和 NLog 定义的格式。它是仅配置的依赖项。也就是说,您通过 app.config 文件配置 Ukadc.Diagnostics 的使用。没有源依赖(您继续通过 System.Diagnostics 而不是通过特殊的 api 进行日志记录)。话虽如此,您应该注意一些限制:

  1. The formatting options currently implemented in Ukadc.Diagnostics really only work correctly when logging with TraceSources. When logging with Trace.Write and Trace.WriteLine the TraceEventCache object is not filled in and that is where most of the formatting objects get their information.

  2. You must use a Ukadc.Diagnostics TraceListener (or a custom listener derived from the Ukadc.Diagnostics base TraceListener) to get the custom formatting to appear in your output. If you found a new super duper rolling file TraceListener, you will have to do some work to use it in conjunction with the Ukadc.Diagnostics formatting. This might be as difficult as reimplementing the listener in terms of the Ukadc.Diagnostics base TraceListener. Or it could be easier, if you could just create a new Ukadc.Diagnostics-based TraceListener that contains the super duper rolling TraceListener, formats the messages per Ukadc.Diagnostics, and then delegates to the contained listener's Write/WriteLine methods.

  1. 目前在 Ukadc.Diagnostics 中实现的格式化选项只有在使用 TraceSources 记录时才能正常工作。使用 Trace.Write 和 Trace.WriteLine 进行日志记录时,未填充 TraceEventCache 对象,大多数格式化对象都在此处获取其信息。

  2. 您必须使用 Ukadc.Diagnostics TraceListener(或从 Ukadc.Diagnostics 基础 TraceListener 派生的自定义侦听器)来使自定义格式显示在您的输出中。如果您发现了一个新的超级欺骗滚动文件 TraceListener,您将需要做一些工作才能将它与 Ukadc.Diagnostics 格式结合使用。这可能与根据 Ukadc.Diagnostics 基础 TraceListener 重新实现侦听器一样困难。或者它可能更容易,如果您可以创建一个新的基于 Ukadc.Diagnostics 的 TraceListener,它包含超级欺骗滚动 TraceListener,根据 Ukadc.Diagnostics 格式化消息,然后委托给包含的侦听器的 Write/WriteLine 方法。

回答by Eugene Ryabtsev

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.dllinto 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?

我最近遇到了类似的情况,看起来现在我们有一个非常适合该任务的工具,即Essential Diagnostics。您可以像下面的代码一样在 app.config 中设置一个侦听器,然后将其Essential.Diagnostics.dll放入同一个文件夹中。无需重新编译。您可以将此用于任何使用 System.Diagnostics 进行跟踪的应用程序,即使您不拥有源。是不是很奇妙?

<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>