首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >防止在TraceSource中使用.NET附带的垃圾前缀

防止在TraceSource中使用.NET附带的垃圾前缀
EN

Stack Overflow用户
提问于 2017-05-21 07:40:30
回答 1查看 168关注 0票数 0

我刚刚设置了使用TraceSource/TraceListener的项目,并添加了一个默认监听器来使用new ConsoleTraceListener()将数据记录到输出窗口。我每一行都会有很多没用的前缀。有什么办法可以防止这种情况发生吗?

代码语言:javascript
复制
FluentFTP Verbose: 0 : InterNetwork: 123.123.123.123
FluentFTP Verbose: 0 : 421 Too many connections (8) from this IP
FluentFTP Verbose: 0 : Disposing FtpClient object...
FluentFTP Information: 0 : QUIT

我想要的只是我追踪的字符串:

代码语言:javascript
复制
InterNetwork: 123.123.123.123
421 Too many connections (8) from this IP
Disposing FtpClient object...
QUIT

我使用的语法是:

代码语言:javascript
复制
private static readonly TraceSource m_traceSource = new TraceSource("FluentFTP") {
    Switch = new SourceSwitch("sourceSwitch", "Verbose") { Level = SourceLevels.All }
};
...
m_traceSource.TraceEvent(TraceLevelTranslation(eventType), 0, message);

编辑:有这个问题的答案-- 这里这里这里,但它们都没有涵盖不能修改TraceListener的用例,只有TraceSource。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-21 14:27:38

我这样做是通过显式地写入跟踪源的listeners...and,而不是调用TraceEvent。如果您愿意这样做,您可以执行类似以下扩展方法的操作。请注意,它必须吃掉由跟踪侦听器引发的所有异常:

代码语言:javascript
复制
static object traceSync = new object( );
static int traceMessageNumber;
internal static void Emit( this TraceSource traceSource, TraceEventType eventType, string message, params object[ ] args )
{
  try
  {
    lock ( traceSync )
    {
      var msgNum = Interlocked.Increment( ref traceMessageNumber );

      if ( traceSource.Switch.ShouldTrace( eventType ) )
      {
        //--> format your message like you want...
        var msg = YourMessageFormatter( msgNum, message, args );

        foreach ( TraceListener listener in traceSource.Listeners )
        {
          try
          {
            listener.WriteLine( msg );
            listener.Flush( );
          }
          catch { }
        }
      }
    }
  }
  catch
  {
    //--> maybe we'll write an event log entry?
  }
}

然后你可以用:

代码语言:javascript
复制
m_TraceSource.Emit( TraceLevelTranslation(eventType), message );
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44094367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档