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

.NET Framework WebAPI中NLog Raygun目标无法记录程序集版本问题

解决.NET Framework WebAPI中NLog Raygun目标无法获取程序集版本的问题

针对你遇到的NLog Raygun目标上报错误时提示Could not find value for entry assembly and version type File,但直接用Raygun能正常追踪版本的问题,提供以下几种可行方案:

方案一:自定义NLog布局渲染器动态获取版本

由于WebAPI在IIS托管环境下,入口程序集并非你的业务程序集,导致NLog默认的版本获取逻辑失效,可通过自定义布局渲染器指定要获取版本的程序集:

  1. 创建自定义布局渲染器类:
using System.Reflection;
using NLog.LayoutRenderers;

[LayoutRenderer("app-version")]
public class AppVersionRenderer : LayoutRenderer
{
    protected override void Append(System.Text.StringBuilder builder, NLog.LogEventInfo logEvent)
    {
        // 替换为你WebAPI项目中任意类的类型,以此定位目标程序集
        var targetAssembly = Assembly.GetAssembly(typeof(HomeController));
        builder.Append(targetAssembly.GetName().Version.ToString());
    }
}
  1. 在NLog配置中注册并使用该渲染器:
<nlog>
  <extensions>
    <!-- 替换为包含上述类的程序集名称 -->
    <add assembly="YourWebApiProjectName" />
  </extensions>
  <targets>
    <target xsi:type="Raygun" name="raygun" ApplicationVersion="${app-version}" />
  </targets>
  <!-- 其余日志规则配置 -->
</nlog>

方案二:代码中动态配置Raygun目标版本

在项目启动时手动获取程序集版本,赋值给NLog的Raygun目标:

using System.Reflection;
using NLog;
using NLog.Targets;

protected void Application_Start()
{
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    
    // 找到配置中的Raygun目标
    var raygunTarget = LogManager.Configuration.FindTargetByName<RaygunTarget>("raygun");
    if (raygunTarget != null)
    {
        // 获取目标程序集版本
        var version = Assembly.GetAssembly(typeof(HomeController)).GetName().Version.ToString();
        raygunTarget.ApplicationVersion = version;
        // 重新加载配置使生效
        LogManager.ReconfigExistingLoggers();
    }
}

方案三:指定Raygun目标的程序集名称与版本类型

如果不想写代码,可尝试在NLog配置中明确指定要获取版本的程序集名称和版本类型:

<target xsi:type="Raygun" name="raygun" 
        UseExecutingAssemblyVersion="false"
        VersionType="AssemblyVersion"
        AssemblyName="YourWebApiProjectName" />

这里的AssemblyName是你WebAPI项目的程序集名称(不含.dll后缀),VersionType可根据需求选择AssemblyVersion或FileVersion。

补充说明

  • 直接设置RaygunWebApiClient.ApplicationVersion仅对原生Raygun客户端生效,NLog的Raygun目标不会复用该配置,所以之前的尝试无效。
  • UseExecutingAssemblyVersion在IIS托管的WebAPI中失效,是因为此时入口程序集为System.Web而非你的业务程序集,无法获取正确版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:24:55