我目前正在使用ASP.NET Core 2.1应用程序,并且使用Serilog进行日志记录。我想在运行时为Serilog实现重新加载应用程序设置文件。
我的目标是在运行时更改日志级别,例如我写到minimumLevel Debug 而不是 Information ,然后保存文件。我想触发设置的实时重新加载。我的appsettings.json
看起来像这样:
{
"serilog": {
"using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
"minimumLevel": "Information",
"writeTo": [
{
"name": "File",
"args": {
"fileSizeLimitBytes": 256000000,
"retainedFileCountLimit": 62,
"rollingInterval": "Day",
"rollOnFileSizeLimit": true,
},
{
"name": "Console",
}
]
}
}
在我的 Program.cs 中,加载带有标志reloadOnChange: true
的设置。
public class Program
{
public static readonly ServiceSettings Settings = new ServiceSettings();
public static void Main(string[] args)
{
//...
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(Path.GetFullPath(CoreServiceBase.Instance.ConfigFilePath), optional: false, reloadOnChange: true)
.AddCommandLine(args)
.Build();
config.Bind(Settings);
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog((hostingContext, loggerConfiguration) =>
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration))
.UseConfiguration(config);
}
}
我的启动看起来像这样:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// ...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Custom application logging
ApplicationLogging.LoggerFactory = loggerFactory;
// ...
}
}
如果我以某种方式更改了appsettings.json,您是否知道如何在运行时重新加载Serilog配置。 =>实时重新加载appsettings.json。
谢谢!
答案 0 :(得分:1)
答案 1 :(得分:1)
您可以使用Serilog.Settings.Reloader
我没有ASP示例,但是在控制台程序上,您可以执行以下操作:
// Service collection
IServiceCollection serviceCollection = new ServiceCollection()
.AddLogging(loggingBuilder =>
loggingBuilder
.AddSerilog(SwitchableLogger.Instance, true)
.AddSerilogConfigurationLoader(configuration, SwitchableLogger.Instance)
);
// Services
using (var services = serviceCollection.BuildServiceProvider())
{
// Create logger
Microsoft.Extensions.Logging.ILogger logger = services.GetService<Microsoft.Extensions.Logging.ILogger<Program>>();
// Write
logger.LogInformation("Hello World");
// Modify config
config.Set("Serilog:WriteTo:0:Args:OutputTemplate", "[{SourceContext}] {Message:lj}{NewLine}{Exception}");
configuration.Reload();
// Write with the previous logger instance, but with different settings
logger.LogInformation("Hello world again");
}
答案 2 :(得分:1)
当前的Serilog实现(2.9.0)无法完全重新加载设置。要解决此问题而又不引入其他依赖关系,请避免创建静态记录器,并按照此处提供的示例进行操作:https://github.com/akovac35/Logging/blob/v1.0.4/src/com.github.akovac35.Logging.Serilog/SerilogHelper.cs
. ./myscript
或者您可以简单地使用Logging.Serilog库,它为此提供实用程序功能。