如何在C#中添加(简单)跟踪? [英] How can I add (simple) tracing in C#?
问题描述
我想对正在编写的C#应用程序进行一些跟踪。可悲的是,我永远无法真正记住它是如何工作的,并希望时不时地检查一下具有参考品质的教程。它应包括:
I want to introduce some tracing to a C# application I am writing. Sadly, I can never really remember how it works and would like a tutorial with reference qualities to check up on every now and then. It should include:
- App.config / Web.config东西,用于注册TraceListeners添加
- 如何设置它
您知道我们应该链接的über教程吗?
Do you know the über tutorial that we should link to?
Glenn Slaven向我指出了正确的方向。将此添加到< configuration />
中的App.config / Web.config中:
Glenn Slaven pointed me in the right direction. Add this to your App.config/Web.config inside <configuration/>
:
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add type="System.Diagnostics.TextWriterTraceListener" name="TextWriter"
initializeData="trace.log" />
</listeners>
</trace>
</system.diagnostics>
这将添加 TextWriterTraceListener
来捕获发送到的所有内容与 Trace.WriteLine
等。
This will add a TextWriterTraceListener
that will catch everything you send to with Trace.WriteLine
, etc.
@DanEsparza指出您应该使用 Trace.TraceInformation
, Trace.TraceWarning
和 Trace.TraceError
而不是 Trace.WriteLine
,因为它们允许您以与 string.Format
相同的方式来格式化消息。
@DanEsparza pointed out that you should use Trace.TraceInformation
, Trace.TraceWarning
and Trace.TraceError
instead of Trace.WriteLine
, as they allow you to format messages the same way as string.Format
.
提示:如果您不添加任何侦听器,则仍可以使用Sysinternals程序 DebugView ( Dbgview.exe
):
Tip: If you don't add any listeners, then you can still see the trace output with the Sysinternals program DebugView (Dbgview.exe
):
推荐答案
我关注了大约五个不同的答案以及以前答案中的所有博客文章,但仍然有问题。我试图将监听器添加到使用 TraceSource.TraceEvent(TraceEventType,Int32,String)
方法跟踪的某些现有代码中,其中 TraceSource
对象用一个字符串初始化,使其成为命名源。
I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String)
method where the TraceSource
object was initialised with a string making it a 'named source'.
对我来说,问题不是创建源和switch元素的有效组合以该源为目标。这是一个示例,该示例将记录到名为 tracelog.txt
的文件中。对于以下代码:
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt
. For the following code:
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
我成功使用以下诊断配置成功登录:
I successfully managed to log with the following diagnostics configuration:
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
这篇关于如何在C#中添加(简单)跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!