c# - 如何以编程方式获取当前的跟踪开关?

标签 c# web-config system.diagnostics

在我的 web.config 中我有:

<system.diagnostics>
  <switches>
    <add name="logLevelSwitch" value="1" />
  </switches>
</system.diagnostics>

有没有一种方法可以调用,例如:

System.Diagnostics.TraceSwitch["logLevelSwitch"]获取当前值?

最佳答案

一旦您在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");
}

此外,根据文档,要使其正常工作:

You must enable tracing or debugging to use a switch. The following syntax is compiler specific. If you use compilers other than C# or Visual Basic, refer to the documentation for your compiler.

To enabledebugging in C#, add the /d:DEBUG flag to the compiler command line when you compile your code, or you can add #define DEBUG to the top of your file. In Visual Basic, add the /d:DEBUG=True flag to the compiler command line.

To enable tracing using in C#, add the /d:TRACE flag to the compiler command line when you compile your code, or add #define TRACE to the top of your file. In Visual Basic, add the /d:TRACE=True flag to the compiler command line.

关于c# - 如何以编程方式获取当前的跟踪开关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13108577/

相关文章:

azure - 企业 Web 库 web.config 目前与 Azure 不兼容?

c# - 如何在堆栈跟踪中获取参数值

c# - 如何加入 SelectList 中的两个字段?

c# - 如何在 F# 或 C# 中将像素绘制到位图上而不是抗锯齿点上?

c# - 如何在配置部分的 XML 属性中存储 "<"?>

asp.net - 如何实现 zopfli 以获得更好的 gzip 压缩?

C# COM 字符串在 C++ BSTR 中损坏

c# - while(reader.Read()) {} 中列表中的重复值

c# - 如何判断一个进程是否已经启动但还没有退出?

c# - ReSharper 的测试运行程序是否可以配置为不显示 Debug.WriteLine() 消息?