使用serilog与azure应用洞察和.Net核心

uz75evzq  于 2023-01-14  发布在  .NET
关注(0)|答案(2)|浏览(125)

目前,我正在使用azure application insights直接记录日志,如Use latest version of Application Insight with .net core API链接所示,一切正常。
但我现在需要借助Azure应用洞察力使用serilog进行日志记录。我甚至对serilog(https://github.com/serilog/serilog-sinks-applicationinsights)做了一些研发。但没有任何想法。您能建议我如何使用.Net core 3.0实现这一点吗

nzk0hqpo

nzk0hqpo1#

请按照以下步骤操作:

    • 首先,安装以下软件包:**

Microsoft.ApplicationInsights.AspNetCore, version 2.14.0
Serilog.AspNetCore, version 3.2.0
Serilog.Sinks.ApplicationInsights, version 3.1.0
Serilog.Settings.Configuration, version 3.1.0

    • 在程序中. cs:**
public class Program
{     
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
           .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
                    .ReadFrom.Configuration(hostingContext.Configuration)
                    .WriteTo.ApplicationInsights(new TelemetryConfiguration{ InstrumentationKey = "xxxxxxxxx" },TelemetryConverter.Traces)
             );                
}
    • 在控制器. cs中**:

    • 试验结果**:

bq3bfh9z

bq3bfh9z2#

下面是如何为aspnetcore设置应用程序配置的信息,但它是为v6.x设置的
https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core?tabs=netcorenew%2Cnetcore6
json(示例)

{
"Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
    "ConnectionString": "Copy connection string from Application Insights Resource Overview"
  }
}

相关问题