c# - 打开和关闭跟踪,并在运行时指定文件路径

标签 c# .net trace system.diagnostics

我对以下问题感到好奇:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <trace autoflush="false" indentsize="4">
      <listeners>
        <add name="logger" type="System.Diagnostics.TextWriterTraceListener"
             initializeData="LoggingFile.txt" />
        <remove name="Default" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

我想在我的解决方案中包含用于记录错误消息和堆栈跟踪的选项。但我需要能够打开和关闭它。通过注释掉 System.Diagnostics 中的所有内容是否可以实现这一点?或者,还有更好的方法?

是否可以指定记录器在运行时写入哪个文件?

最佳答案

您可以使用SourceSwitch,它允许您跟踪不同级别的消息。首先向 app.config

添加一些设置
<system.diagnostics>
  <sources>
    <source name="TraceTest" switchName="SourceSwitch"
            switchType="System.Diagnostics.SourceSwitch">
      <listeners>
            <!-- choose one or use multiple TraceListeners -->
            <add name="console" type="System.Diagnostics.ConsoleTraceListener"
                 initializeData="false"/>
            <add name="file" type="System.Diagnostics.TextWriterTraceListener"
                 initializeData="error.log"/>
            <remove name ="Default"/>
      </listeners>
    </source>
   </sources>
   <switches>
    <!--  MSDN: 4 verbose Information, Information 3, Warning 2, Error 1, -->
    <add name="SourceSwitch" value="Error"/>
  </switches>
  <trace autoflush="true" indentsize="4"/>
</system.diagnostics>

在您的应用程序中,您可以使用 TraceSource 来跟踪消息引用 app.config 中定义名称的对象

TraceSource ts = new TraceSource("TraceTest");
ts.TraceEvent(TraceEventType.Information, 123, "event info");
ts.TraceEvent(TraceEventType.Error, 123, "event error");
ts.TraceEvent(TraceEventType.Warning, 123, "event warning");

ts.TraceInformation("any text");
ts.Flush();
ts.Close();

有关一些常见信息,请查看 How to: Use TraceSource ...在 MSDN。使用 Google 博士我找到了相关的 question at SO指的是very good blogpost关于此事。

我想指出一件事......

更改监听器写入跟踪消息的级别

The configuration file initializes the settings for the trace source at the time the application is initialized. To change those settings you must change the configuration file and restart the application or programmatically refresh the application using the TraceRefresh method. The application can dynamically change the properties set by the configuration file to override any settings specified by the user. For example, you might want to assure that critical messages are always sent to a text file, regardless of the current configuration settings.

关于c# - 打开和关闭跟踪,并在运行时指定文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12403332/

相关文章:

c# - IIS6 WebService 下 Environment.GetFolderPath(Environment.SpecialFolder.ApplicationFolder) 返回的路径错误

c# - 在丰富的文本框中包装文本,但不包装它

c# - 在 FlowLayoutPanel 中插入用户控件

c# - 将时间戳添加到 Trace.WriteLine()

python - 使用脚本或正则表达式将 "printf"添加到每个函数

c# - 将 TreeNodeCollection 转换为 List<TreeNode>

c# - 你用过的最酷的 C# LINQ/Lambdas 技巧?

c# - 无法弄清楚异常消息

c# - 以编程方式确定是否启用了 Windows 8 安全启动

python - 可以让 Python 生成类似于 bash 的 set -x 的跟踪吗?