AppInsights只保存遥测数据,而不保存在IIS上托管的.Net Core Web应用程序的日志。
创始人
2024-09-10 08:00:08
0次

要解决这个问题,你可以使用Serilog库来同时将日志消息发送到AppInsights和文件中。以下是一个示例代码来实现这个解决方案:

首先,使用NuGet包管理器安装Serilog和Serilog.Sinks.ApplicationInsights。

然后,将以下代码添加到你的.NET Core Web应用程序的Startup.cs文件中的ConfigureServices方法中:

using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Extensions.Logging;

public void ConfigureServices(IServiceCollection services)
{
    // Add Application Insights
    services.AddApplicationInsightsTelemetry();

    // Configure Serilog
    var instrumentationKey = Configuration["ApplicationInsights:InstrumentationKey"];
    var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
    telemetryConfiguration.InstrumentationKey = instrumentationKey;

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Information()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
        .MinimumLevel.Override("System", LogEventLevel.Warning)
        .WriteTo.ApplicationInsights(telemetryConfiguration, TelemetryConverter.Traces)
        .WriteTo.File("logs.txt", rollingInterval: RollingInterval.Day)
        .CreateLogger();

    // Replace the default ILoggerFactory with Serilog
    services.AddSingleton(new SerilogLoggerFactory(Log.Logger, true));
}

其中,instrumentationKey是你的AppInsights仪表板中的Instrumentation Key。

最后,在Configure方法中添加以下代码:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // ...

    // Add Serilog as the logging middleware
    loggerFactory.AddSerilog();

    // ...
}

现在,你的应用程序将同时将日志消息发送到AppInsights和文件中。你可以根据需要修改Serilog的配置,例如调整日志级别、日志文件的名称和位置等。

相关内容

热门资讯

技巧知识分享!wepoker网... wepoker网页版透视方法AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏...
玩家必备教程!!wepoker... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
一分钟教会你!WPK德州局,德... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
技术分享!wepoker永久免... 一款 AI 游戏攻略黑科技工具上线,查攻略效率直接开挂。它整合版本更新、装备搭配、BOSS 打法、牌...
推荐一款!!德普辅助app,w... wepoker透视方法AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻略数...
一分钟揭秘!wpk辅助器是真的... 一分钟揭秘!wpk辅助器是真的吗,WPK有挂么辅助脚本(从来真的有辅助挂)主打本地运行的 AI 黑科...
一分钟了解!!wepoker透... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
信息共享!wpk俱乐部有没有辅... 信息共享!wpk俱乐部有没有辅助,德扑之星开挂透视教程工具(最初有辅助器)AI 智能体黑科技再上新,...
必胜教程!wepokerh5破... 必胜教程!wepokerh5破解,WPK透视软件下载(原来有辅助)主打本地运行的 AI 黑科技工具迎...
热点讨论!德普之星有透视辅助吗... 热点讨论!德普之星有透视辅助吗,德扑之星可以装挂吗工具(其实是有辅助器)AI 智能体黑科技再上新,自...