You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#的NLog日志中自动添加方法名(配置修改)

解决NLog自动记录方法名的问题

直接修改nlog.config里的File目标layout配置,加入NLog内置的${callsite}变量就能自动捕获方法名,不用手动编写。具体操作如下:

  1. 找到你的File目标配置块
    通常你的File目标配置大概长这样:

    <target name="file" xsi:type="File" fileName="logs/${shortdate}.log" layout="${longdate} ${level} ${message}" />
    
  2. 修改layout,添加方法名变量

    • 如果你想显示完整类名+方法名,把layout改成:

      <target name="file" xsi:type="File" fileName="logs/${shortdate}.log" layout="${longdate} ${level} ${callsite} ${message}" />
      

      日志输出示例:2024-05-20 14:30:00.123 DEBUG MyNamespace.MyClass.MyMethod Check CheckFixstation ...

    • 如果你只想显示纯方法名(不带类名),用带参数的${callsite}:

      <target name="file" xsi:type="File" fileName="logs/${shortdate}.log" layout="${longdate} ${level} ${callsite:className=false} ${message}" />
      

      日志输出示例:2024-05-20 14:30:00.123 DEBUG MyMethod Check CheckFixstation ...

  3. 确认调用站点捕获启用
    默认NLog已经启用callsite捕获,保险起见可以检查nlog根节点是否开启了配置异常抛出(方便排查问题):

    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          throwConfigExceptions="true">
      <!-- 你的目标和规则配置 -->
    </nlog>
    
  4. 性能小提示
    ${callsite}会有轻微的性能开销,如果是高并发场景,可根据需求调整:比如Release模式下可以选择关闭,或者用${callsite:skipFrames=1}(如果有自己封装的日志静态类,需要跳过封装层的调用帧)。

改完之后,直接调用Log.Debug("Check CheckFixstation ...");就能自动在日志里带上正确的方法名,再也不用手动复制粘贴了。

内容的提问来源于stack exchange,提问作者Dominique

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:30:06