Set Serilog minimum level from environment variable
Set Serilog minimum level from environment variable
问题
Is it possible to setup Serilog minimum log level from environment variable?
If I try to configure it like this
"Serilog": {
"MinimumLevel": "%LOG_LEVEL%",
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [v{SourceSystemInformationalVersion}] {Message}{NewLine}{Exception}",
"pathFormat": "%LOG_FOLDER%/sds-osdr-domain-saga-host-{Date}.log",
"retainedFileCountLimit": 5
}
}
]
}
it returns error
The value %LOG_LEVEL% is not a valid Serilog level.
Is it possible to propagate log level from environment variable somehow?
回答
I think you are asking about configuration by environment which is not specific to serilog.
If the LOG_LEVEL
is fixed with the specific environment (development, staging or production), you can set the each LOG_LEVEL
in appsettings.<EnvironmentName>.json
, and set configuration like this:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.Build();
If you need to config the LOG_LEVEL
from environment variable in docker-compose file or kubernetes deployment file, then you can read values from environment variables by calling AddEnvironmentVariables
:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false)
.AddEnvironmentVariables()
.Build();
And set the environment Serilog:MinimumLevel
in windows or ``Serilog__MinimumLevel` in linux and mac.
/ serilog-settings-configuration
After installing this package, use ReadFrom.Configuration()
and pass an IConfiguration
object.
static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
logger.Information("Hello, world!");
}
This example relies on the Microsoft.Extensions.Configuration.Json, Serilog.Sinks.Console, Serilog.Sinks.File, Serilog.Enrichers.Environment and Serilog.Enrichers.Thread packages also being installed.
For a more sophisticated example go to the sample folder.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-08-16 xpath injection
2017-08-16 各种浏览器的兼容css
2017-08-16 vs输出窗口,显示build的时间
2017-08-16 sass