如何使用 serilog 的应用程序洞察接收器设置最小日志级别 [英] How to set the minimum loglevel with serilog's application insights sink
问题描述
我正在使用 Serilog 记录应用程序洞察,但我只得到日志级别警告、错误和要记录的关键.在 appsettings.json 中,我将最小日志级别设置为详细,这会记录文件和控制台接收器的所有内容.
I'm using Serilog to log to application insights, but I am only getting the log levels warning, error, and critical to be logged. In appsettings.json, I have the minimum loglevel set to verbose, and this logs everything with the file and console sinks.
默认情况下,应用洞察只能记录警告及以上.在代码中(在配置日志记录中),我可以添加一个过滤器来覆盖警告及以上的默认值.我更喜欢在 appsettings 中执行此操作,并使用其他日志记录配置.
By default, application insights can only logs Warning and above. In code (in configure logging), I can add a filter to override this default of warning and above. I preferer to do this in appsettings, with the other logging configuration.
我如何使用 appsettings 来允许 Serilog 将所有级别记录到 Application Insights?
How so I use appsettings to allow Serilog to log all levels to Application Insights?
- 我在应用程序洞察中获得了一些日志,因此连接性是工作.
- 我在日志文件和控制台上看到所有日志级别.
在配置日志记录的地方,如果我添加 LogLevel 文件管理器(注释掉),我可以让它工作.我需要在应用设置中工作.
Where configuting logging,if I add LogLevel filer (commented out) I can make it work. I needs to work from appsettings.
host.ConfigureLogging(
loggingBuilder =>
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
loggingBuilder.AddApplicationInsights();
loggingBuilder.AddSerilog(logger, dispose: true);
//loggingBuilder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);
}
);
这是我的代码和结果:
这是我的应用设置:
"Serilog": {
"AllowedHosts": "*",
"Enrich": [ "WithMachineName" ],
"MinimumLevel": {
"Default": "Verbose",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"fileSizeLimitBytes": "1048576",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact , Version=1.0.0.0, Culture=neutral, PublicKeyToken=24c2f752a8e58a10",
"path": "c:\\LogFiles\\Publisher\\Test1\\_log.txt",
"retainedFileCountLimit": null,
"rollingInterval": "Day",
"rollOnFileSizeLimit": "true"
}
},
{
"Name": "ApplicationInsights",
"Args": {
"restrictedToMinimumLevel": "Verbose",
"telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
}
}
]
},
推荐答案
这是我的测试结果:
我创建了我的 asp.net core mvc 应用程序,这是我的 appsettings.json:
I created my asp.net core mvc application and here's my appsettings.json:
{
"AllowedHosts": "*",
"Serilog": {
"Using": [],
"MinimumLevel": "Verbose",
"WriteTo": [
{
"Name": "Console",
"Args": {
"restrictedToMinimumLevel": "Verbose",
"outputTemplate": "{Timestamp:HH:mm:ss.fff zzz} [{Level}] {Message} {NewLine}{Exception}"
}
},
{
"Name": "ApplicationInsights",
"Args": {
"instrumentationKey": "instrument_key_here",
"restrictedToMinimumLevel": "Verbose",
"telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId"],
"Properties": {
"Application": "Sample"
}
}
}
我的program.cs,添加读取配置代码并添加UseSerilog():
My program.cs, add read configuration code and add UseSerilog():
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
namespace serilog_appsetting_file_appinsights
{
public class Program
{
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseSerilog();
}
}
我的包裹:
<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.17.0" />
<PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="3.1.0" />
</ItemGroup>
我的控制器文件:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Serilog;
using serilog_appsetting_file_appinsights.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace serilog_appsetting_file_appinsights.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
Log.Verbose("serilog_verbose_info");
Log.Debug("serilog_debug_info");
Log.Information("serilog_information_info");
Log.Warning("serilog_warning_info");
Log.Error("serilog_error_info");
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
在本地主机调试时,我们可以看到应用洞察捕获这样的日志,并看到控制台日志
When debuging in localhost, we can see app insights capturing logs like this, and see console log
这篇关于如何使用 serilog 的应用程序洞察接收器设置最小日志级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!