Configure Column Options for Serilog Sinks MsSqlServer in AppSettings.json

浪尽此生 提交于 2019-12-06 04:50:08

For accessing Serilog from appsettings in Code, you could bind Serilog node to Serilog class.
Here are the detail steps.
1. Create Serilog Configuration Class

    public class SerilogConfiguration
{
    public LogEventLevel MinimumLevel { get; set; }
    public List<WriteTo> WriteTo { get; set; }
}
public class WriteTo
{
    public string Name { get; set; }
    public Args Args { get; set; }
}
public class Args
{
    public string ConnectionString { get; set; }
    public string TableName { get; set; }
    public List<StandardColumn> Add { get; set; }
    public List<StandardColumn> Remove { get; set; }
}
  1. Configure appsettings.json

Code:

{
    "Serilog": {
    "MinimumLevel": "Error",
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "<our connection string>",
          "tableName": "Log",
          "Remove": [ "Properties" ],
          "Add": [ "LogEvent" ]
        }
      }
    ]
  }
}
  1. Bind appsetting.json to class

    public void ConfigureServices(IServiceCollection services)
    {           
        services.Configure<SerilogConfiguration>(Configuration.GetSection("Serilog"));            
    }
    
  2. Access Configuration

    public class HomeController : Controller    {
    private readonly SerilogConfiguration _configuration;
    public HomeController(IOptions<SerilogConfiguration> configuration)
    {
        _configuration = configuration.Value;
    }       
    
    public IActionResult AppSettings()
    {
        var columnOptions = new ColumnOptions();
        var MSSqlServer = _configuration.WriteTo.Where(wt => wt.Name == "MSSqlServer").FirstOrDefault();
        // Don't include the Properties XML column.
        foreach(var columnRemove in MSSqlServer.Args.Remove)
        {
            columnOptions.Store.Remove(columnRemove);
        }
        // Do include the log event data as JSON.
        foreach (var columnAdd in MSSqlServer.Args.Add)
        {
            columnOptions.Store.Add(columnAdd);
        }
    
        Log.Logger = new LoggerConfiguration()
            .WriteTo.MSSqlServer(MSSqlServer.Args.ConnectionString, MSSqlServer.Args.TableName, columnOptions: columnOptions,
                restrictedToMinimumLevel: _configuration.MinimumLevel)
            .CreateLogger();
        return Ok("OK");
    }    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!