c# - 当 .Net Thread 没有名称时,如何使用 NLog 打印 threadid 而不是 threadname?

标签 c# .net multithreading logging nlog

我有如下 NLog 配置。

如果存在,它会打印线程的名称。否则我会得到空字符串而不是线程名称。

问题:我如何存档下面的行为?

  • 如果线程有名称 - 打印线程名称
  • 否则 - 打印 ManagedThreadId(例如,与 threadid NLog 变量相同)。

  • 当前配置示例:

    <variable name="defaultLayout" value="${date} ${level} [${threadname}] ${logger} - ${message} ${exception:format=ToString}"/>
    
    <targets async="true">
      <target name="ConsoleAppender" 
              type="ColoredConsole" 
              layout="${var:defaultLayout}" />
    </targets>
    

    请注意:我想避免打印两个变量,例如这个布局没用:... [${threadname}-${threadid}] ...

    最佳答案

    TLDR:使用这个 - ${threadname:whenEmpty=${threadid}}
    所以正确的配置:

    <variable name="defaultLayout" value="${date} ${level} [${threadname:whenEmpty=${threadid}}] ${logger} - ${message} ${exception:format=ToString}"/>
    
    <targets async="true">
       <target name="ConsoleAppender" 
          type="ColoredConsole" 
          layout="${var:defaultLayout}" />
    </targets>
    

    关于c# - 当 .Net Thread 没有名称时,如何使用 NLog 打印 threadid 而不是 threadname?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54889134/

    相关文章:

    c# - 为什么会出现 "Could not create an instance of type Microsoft.AspNetCore.Http.IFormFile"错误?

    .net - NetSuite API 创建订单时出错

    c# - 是否可以读取实习生池中的所有字符串?

    java - 使用 FutureTask 比 Callable 有什么优势?

    c# - 在线程中处置非托管资源

    c# - 我应该使用 Closing 事件还是重写 OnClosing?

    c# - Ninject:将接口(interface)绑定(bind)到多个实现

    c# - 网络服务器在 IHostedService 启动之前开始处理请求

    c# - 通过 FileSystemWatcher 减少受监控文件的数量

    Java - 使用 ImageIO 进行多线程处理