简体   繁体   English

Serilog - 单独的信息文件,异常使用 appsetting.json

[英]Serilog - Separate files for Information, exception using appsetting.json

I am writing all logs into one file(s) using rolling.我正在使用滚动将所有日志写入一个文件。 But I want to separate them by Information , Warning and Exceptions rolling files.但我想通过InformationWarningExceptions滚动文件将它们分开。

my current configuration is like this我目前的配置是这样的

     "Serilog": {
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
          "pathFormat": "logs\\log-{Hour}.log",
          "rollOnFileSizeLimit ": true,
          "retainedFileCountLimit ": null,
          "rollingInterval": "Hour",
          "fileSizeLimitBytes": 5000000
        }
      }
    ]
  },

class class

public ILogger GetLogger()
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        _logger =
            new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .CreateLogger();

        return _logger ;
    }

In Serilog you could do this separation either via sub-loggers or via Serilog.Sinks.Map .在 Serilog 中,您可以通过子记录器或通过Serilog.Sinks.Map进行这种分离。

You wouldn't be able to configure the whole pipeline via appsetting.json but you can easily configure the path of each file in appsetting.json using a custom key of your choice, and use that when configuring the log pipeline via code.您将无法通过appsetting.json配置整个管道,但您可以使用您选择的自定义密钥轻松配置appsetting.json中每个文件的路径,并在通过代码配置日志管道时使用它。


Example using sub-loggers with a filter applied to each of them:使用子记录器的示例,每个子记录器都应用了过滤器:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Logger(c =>
        c.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug)
            .WriteTo.File("Debug.log"))
    .WriteTo.Logger(c =>
        c.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
            .WriteTo.File("Error.log"))
    .CreateLogger();

Log.Debug("This goes to Debug.log only");
Log.Error("This goes to Error.log only");

Log.CloseAndFlush();

Example using Serilog.Sinks.Map mapping each LogEventLevel to a different file.使用Serilog.Sinks.Map将每个LogEventLevel映射到不同文件的示例。

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Map(evt => evt.Level, (level, wt) => wt.File($"{level}.log"))
    .CreateLogger();

Log.Debug("This goes to Debug.log only");
Log.Error("This goes to Error.log only");

Log.CloseAndFlush();

i have not tested but by extrapoling the documentation: you could try to create 2 sections in you appconf file我没有测试,但通过推断文档:您可以尝试在 appconf 文件中创建 2 个部分

  "ErrorLog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
          "pathFormat": "logs\\ Errorlog-{Hour}.log",       
          "rollingInterval": "Hour",
          "restrictedToMinimumLevel": "Error"
        }
      }
    ]
  },
  "InfoLog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
          "pathFormat": "logs\\ Infolog-{Hour}.log",
          "rollingInterval": "Hour",
          "restrictedToMinimumLevel": "Information"
        }
      }
    ]
  }

and you create 2 loggers:然后创建 2 个记录器:

    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();


        var errorSection = configuration.GetSection("ErrorLog");
        var infoSection = configuration.GetSection("InfoLog");


        _errorlog = new LoggerConfiguration()
            .ReadFrom
            .ConfigurationSection(errorSection)
            .CreateLogger();

        _infolog = new LoggerConfiguration()
            .ReadFrom
            .ConfigurationSection(infoSection)
            .CreateLogger();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将值更新到 appsetting.json? - How to update values into appsetting.json? Azure function 读取应用设置。json - Azure function read appsetting.json 读取屏幕上文件 appsetting.json 中的所有数组值,读取 id = 555 的书籍信息 - Read all the array values in file appsetting.json on the screen and read book information with id = 555 在.NET CORE中,如何执行XUnit测试以检查和验证从AppSetting.json加载的正确信息 - In .NET CORE, How to perform XUnit test to check and validate correct information loading from AppSetting.json 将值保存到 appsetting..NET 核心中的 json - Saving values to appsetting.json in .NET Core 从类中的appsetting.json获取价值 - Get Value from appsetting.json in class appsetting.json 中应该包含哪些值? - What values should be in appsetting.json? 如何使用 IConfiguration 从 appsetting.json 读取值的子数组? - How to read sub array of values from appsetting.json using IConfiguration? 在 .net core 3.1 中使用来自 appsetting.json 的凭据时,授权不起作用 - Authorization not working when using credentials from appsetting.json in .net core 3.1 使用 appsetting.json 文件中的 .NET Core 6.0 设置数据库上下文 - Setup database context using .NET Core 6.0 from appsetting.json file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM