c# - 如何从 TraceListener 输出中删除进程名称?

标签 c# .net logging tracelistener

我有代码:

 var listener = new TextWriterTraceListener(@"C:\logs\1.log", "myListener")
        {
            TraceOutputOptions = TraceOptions.DateTime
        };

        Trace.Listeners.Add(listener);
        Trace.TraceInformation("Starting...");

输出为 MyProgram.vshost.exe Information: 0 : Starting...DateTime=2016-07-07T10:43:10.5147858Z 如何告诉监听器不要打印进程名称?

最佳答案

不幸的是,这似乎是不可能的。

我反编译了那个监听器,发现没有这个选项。 但仍有希望。

您可以像这样实现自己的监听器:

public class MyListener : TextWriterTraceListener {

      public MyListener(Stream s) : base(s) {
      }

      public MyListener(string s, string s1) : base(s, s1) {
      }

      public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) {
        if (this.Filter != null && !base.Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null))
          return;
        this.WriteLine(message);
        this.WriteFooter(eventCache);
      }

      private bool IsEnabled(TraceOptions opts) {
        return (uint)(opts & this.TraceOutputOptions) > 0U;
      }

      private void WriteFooter(TraceEventCache eventCache) {
        if (eventCache == null)
          return;
        this.IndentLevel = this.IndentLevel + 1;
        if (this.IsEnabled(TraceOptions.ProcessId))
          this.WriteLine("ProcessId=" + (object)eventCache.ProcessId);
        if (this.IsEnabled(TraceOptions.LogicalOperationStack)) {
          this.Write("LogicalOperationStack=");
          Stack logicalOperationStack = eventCache.LogicalOperationStack;
          bool flag = true;
          foreach (object obj in logicalOperationStack) {
            if (!flag)
              this.Write(", ");
            else
              flag = false;
            this.Write(obj.ToString());
          }
          this.WriteLine(string.Empty);
        }
        if (this.IsEnabled(TraceOptions.ThreadId))
          this.WriteLine("ThreadId=" + eventCache.ThreadId);
        if (this.IsEnabled(TraceOptions.DateTime))
          this.WriteLine("DateTime=" + eventCache.DateTime.ToString("o", (IFormatProvider)CultureInfo.InvariantCulture));
        if (this.IsEnabled(TraceOptions.Timestamp))
          this.WriteLine("Timestamp=" + (object)eventCache.Timestamp);
        if (this.IsEnabled(TraceOptions.Callstack))
          this.WriteLine("Callstack=" + eventCache.Callstack);
        this.IndentLevel = this.IndentLevel - 1;
      }
    }

关于c# - 如何从 TraceListener 输出中删除进程名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38243927/

相关文章:

C#在内存中以特定大小剪切图像而不保存文件

java - 删除文件后,Logback 不会重新创建日志文件

c# - 为 Log4Net 中的特定异常设置日志记录级别(对于 Episerver)

.net - 使用 protected 配置对web.config进行加密毫无意义吗?

c# - ListView 分组和排序

c# - 自定义 MembershipProvider 初始化方法

具有前端的 Java 简单分析/事件流处理

c# - 可以将 "All"项添加到 Flags 枚举吗?

c# - 如何使用 Roslyn 将 C# 关键字替换为字符串替代项?

C# 多线程应用程序 - 结构?