Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 789
Mr. Pumpkin Avatar asked Mar 18 '18 17:03

Mr. Pumpkin


2 Answers

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.

like image 50
Feiyu Zhou Avatar answered Oct 24 '22 20:10

Feiyu Zhou


After some thinking I ended up with the tiny class below

public class EnvironmentVariableLoggingLevelSwitch : LoggingLevelSwitch
{
    public EnvironmentVariableLoggingLevelSwitch(string environmentVariable)
    {
        LogEventLevel level = LogEventLevel.Information;
        if (Enum.TryParse<LogEventLevel>(Environment.ExpandEnvironmentVariables(environmentVariable), true, out level))
        {
            MinimumLevel = level;
        }
    }
}

and using it when configure logger

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(Configuration)
    .MinimumLevel.ControlledBy(new EnvironmentVariableLoggingLevelSwitch("%LOG_LEVEL%"))
    .CreateLogger();

So, if you don't declare environment variable you still may configure logging level from config file, or override it with environment variable.

like image 39
Mr. Pumpkin Avatar answered Oct 24 '22 20:10

Mr. Pumpkin