在我的web.config中,我有:

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

有没有一种我可以打电话的方式,例如:
System.Diagnostics.TraceSwitch["logLevelSwitch"]获取当前值?

最佳答案

web.config文件中定义了switch值之后,可以通过创建一个具有相同名称的 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");
}

此外,根据文档,要使其正常工作,请执行以下操作:

08-25 05:33