【问题标题】:How can I get the current Trace Switch programatically?如何以编程方式获取当前的 Trace Switch?
【发布时间】:2012-10-28 11:52:06
【问题描述】:
在我的web.config 我有:
<system.diagnostics>
<switches>
<add name="logLevelSwitch" value="1" />
</switches>
</system.diagnostics>
有没有办法可以调用,例如:
System.Diagnostics.TraceSwitch["logLevelSwitch"]获取当前值?
【问题讨论】:
标签:
c#
web-config
system.diagnostics
【解决方案1】:
在web.config 文件中定义开关值后,通过创建同名的TraceSwitch 即可轻松地从应用程序中获取此值:
private static TraceSwitch logSwitch = new TraceSwitch("logLevelSwitch",
"This is your logLevelSwitch in the config file");
public static void Main(string[] args)
{
// you can get its properties value then:
Console.WriteLine("Trace switch {0} is configured as {1}",
logSwitch.DisplayName,
logSwitch.Level.ToString());
// and you can use it like this:
if (logSwitch.TraceError)
Trace.WriteLine("This is an error");
// or like this also:
Trace.WriteLineIf(logSwitch.TraceWarning, "This is a warning");
}
此外,根据文档,要使其正常工作:
您必须启用跟踪或调试才能使用开关。以下
语法是编译器特定的。如果您使用 C# 以外的编译器或
Visual Basic,请参阅编译器的文档。
要在 C# 中启用调试,请将 /d:DEBUG 标志添加到编译器命令行
当你编译你的代码时,或者你可以在顶部添加#define DEBUG
你的文件。在 Visual Basic 中,将 /d:DEBUG=True 标志添加到编译器
命令行。
要在 C# 中启用跟踪,请将 /d:TRACE 标志添加到
编译代码时的编译器命令行,或将#define TRACE 添加到文件顶部。在 Visual Basic 中,添加 /d:TRACE=True
标记到编译器命令行。