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

.NET Core 3控制台应用NLog结合Application Insights无日志输出求助

Problem: Application Insights Not Receiving NLog Logs in .NET Core 3 Console App

I'm setting up a .NET Core 3 console app that integrates Application Insights with NLog, but I'm hitting a wall. Here's my current configuration:

Program.cs

.ConfigureLogging((hostingContext, logging) => { 
    logging.ClearProviders(); 
    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); 
    logging.AddNLog(NLog.LogManager.LoadConfiguration("nlog.config").Configuration); 
}) 
.ConfigureServices((hostContext, services) => { 
    services.SetupConfiguration(hostContext.Configuration); 
    services.AddApplicationInsightsTelemetryWorkerService("--AI-Key--"); 
})

nlog.config

<extensions> 
    <add assembly="NLog.Web.AspNetCore"/> 
    <add assembly="Microsoft.ApplicationInsights.NLogTarget" /> 
</extensions> 
<!-- the targets to write to --> 
<targets> 
    <target name="Console" xsi:type="Console" layout="${longdate} ${level} ${message}"/> 
    <target xsi:type="ApplicationInsightsTarget" name="appInsights" /> 
</targets> 
<!-- rules to map from logger name to target --> 
<rules> 
    <!--All logs, including from Microsoft--> 
    <logger name="*" minlevel="Trace" writeTo="Console" /> 
    <logger name="*" minlevel="Trace" writeTo="appInsights" /> 
</rules>

appsettings.json

"Logging": { 
    "LogLevel": { 
        "Default": "Debug" 
    } 
}, 
"ApplicationInsights": { 
    "InstrumentationKey": "--AI-Key--" 
}

I'm using constructor injection to get an ILogger instance and calling _logger.LogDebug("something"), but no logs show up in Application Insights. Worse, my output window is filled with messages starting with "Application Insights Telemetry (unconfigured):.....". There's barely any docs on this specific issue, so I'd love some pointers on how to fix this.


Troubleshooting & Fixes

Let's walk through the likely issues and how to resolve them:

Right now, your ApplicationInsightsTarget in nlog.config doesn't know where to send logs—you haven't supplied the instrumentation key. Update the target to pull the key directly from your appsettings.json (keeps config centralized):

<target xsi:type="ApplicationInsightsTarget" name="appInsights" 
        instrumentationKey="${configsetting:name=ApplicationInsights.InstrumentationKey}" />

2. Fix Initialization Order in Program.cs

You're loading NLog before setting up Application Insights services, which means the NLog target can't access the properly configured telemetry client. Adjust the order to register Application Insights first, then let NLog hook into the service provider:

.ConfigureLogging((hostingContext, logging) => { 
    logging.ClearProviders(); 
    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); 
})
.ConfigureServices((hostContext, services) => { 
    services.SetupConfiguration(hostContext.Configuration); 
    // Register Application Insights first, using the key from config
    services.AddApplicationInsightsTelemetryWorkerService(
        hostContext.Configuration["ApplicationInsights:InstrumentationKey"]
    ); 
    // Now add NLog, letting it use the registered services
    services.AddNLog();
})

Double-check that you have the NLog.Web.AspNetCore package installed (you reference it in nlog.config, but confirm it's in your csproj).

3. Manually Flush Telemetry (Critical for Console Apps)

Unlike web apps, console apps don't automatically flush telemetry when shutting down. If your app exits immediately after logging, logs might never be sent to Application Insights. Inject a TelemetryClient into your main service and flush it before exiting:

public class MyWorkerService
{
    private readonly ILogger<MyWorkerService> _logger;
    private readonly TelemetryClient _telemetryClient;

    public MyWorkerService(ILogger<MyWorkerService> logger, TelemetryClient telemetryClient)
    {
        _logger = logger;
        _telemetryClient = telemetryClient;
    }

    public async Task RunAsync()
    {
        _logger.LogDebug("something");
        
        // Flush and wait for telemetry to send
        _telemetryClient.Flush();
        await Task.Delay(1000); // Give it a second to complete the request
    }
}

4. Verify Log Level Filtering

Your appsettings.json sets the default log level to Debug, and NLog's rule uses minlevel="Trace", but the .NET logging pipeline might still filter logs. Ensure:

  • There are no namespace-specific log level overrides in appsettings.json that block Debug logs for your logger.
  • If using ILogger<T>, your namespace isn't excluded from the log rules.

5. Check Package Version Compatibility

Mismatched package versions are a common culprit. Make sure these packages are compatible with .NET Core 3:

  • Microsoft.ApplicationInsights.NLogTarget
  • NLog.Web.AspNetCore
  • Microsoft.ApplicationInsights.WorkerService

After making these changes, run your app again. It might take 2-5 minutes for logs to appear in Application Insights, but the "unconfigured" warning should disappear immediately, and logs should start showing up in the Logs section of your AI resource.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:16:26