Serilog多个文件appsettings.json

时间:2019-06-03 12:15:49

标签: c# serilog

我正在尝试配置serilog以写入多个文件,没有任何运气。 使用这种配置,它只是写入第二个文件吗?

{
  "AllowedHosts": "*",
  "Serilog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "c:\\temp\\audit-.log",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Information"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "c:\\temp\\error-.log",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Error"
        }
      }
    ]
  }
}

或者有什么方法可以将许多记录器加载到appsettings.json中具有不同配置的软件中。像这样吗?

var errorLogConfiguration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
    .AddEnvironmentVariables()
    .Build();

_log = new LoggerConfiguration()
    .ReadFrom
    .Configuration(errorLogConfiguration)
    .CreateLogger();

5 个答案:

答案 0 :(得分:2)

经过一段时间的错误后,由于缺乏有关Serilog的文档,我的发现重试并几乎放弃了。他们在GitHub上工作:https://github.com/serilog/serilog-filters-expressions/issues/27。几乎每个线程都会得出与必须创建SUBLOGGER相同的结论。这是我的实现。为此,您需要以下插件:

  • Serilog筛选器
  • Serilog水槽
  • Serilog异步

    "Serilog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo:Information": { //this name here can be changed
      "Name": "Logger", //this name here is essential
      "Args": {
        "configureLogger": {
          "Filter": [
            {
              "Name": "ByIncludingOnly",
              "Args": {
                "expression": "@Level = 'Information'"
              }
            }
          ],
          "WriteTo": [
            {
              "Name": "Async", //i use async plugin from serilog
              "Args": {
                "configure": [
                  {
                    "Name": "File",
                    "Args": {
                      "path": "Logs/Log_.txt",
                      "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
                      "rollingInterval": "Day",
                      "retainedFileCountLimit": 7
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    },
    

答案 1 :(得分:1)

我找到了解决方案。为appsettings.json,ErrorLog和AuditLog创建了单独的部分。

ash

现在我可以创建2个单独的记录器:

bash

哪个更适合我的需求。

答案 2 :(得分:0)

我对此问题进行了一些测试。好消息是您的配置有效。您的错误文件可能未创建,因为未记录任何错误。

当第一条消息记录到该文件时,Serilog将创建日志文件。如果您运行此简单程序并取消注释错误记录,则可以确认这一点。

class Program
{
    static void Main(string[] args)
    {
        var errorLogConfiguration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json", optional: false, reloadOnChange: true)
            .Build();

        var log = new LoggerConfiguration()
            .ReadFrom
            .Configuration(errorLogConfiguration)
            .CreateLogger();
        log.Warning("Warning");
        log.Error("Error");
    }
}

答案 3 :(得分:0)

关于通过配置文件进行的记录器设置的文档很少。任何人都可以帮忙-这只是使用记录仪设置的一个示例。在示例中-所有日志都写在一个sample.txt中。在一个单独的文件中登录某个API / api / health的调用,并且不包含在sample.txt中。还有一个示例广告-IMyLogger-写入单独的SampleMy.txt。您可以添加许多部分,然后按不同条件划分日志。最好将本地日志记录级别设置为最低,它们将被全局级别覆盖。全局过滤器将从所有子记录器中排除日志(我不使用它)。 PS对不起,英语不好)

"Serilog": {
    "MinimumLevel": "Information", //<- global error level. Ovveride all local error level
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "MinimumLevel": "Debug", // <- local error level. 
            //Only records with Information logging level will be written to the log file
           //but if ovveride global level to Debug, and dont override local error level -> it will still be global
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "log\\SampleHealthCheck-.txt", //write health-check log in different file
                  "rollingInterval": "Day",
                  "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [CorrId:{CorrelationId}] [Op:{OperationId}] [U:{UserName}] {Message:lj}{NewLine}{Exception}"
                }
              }
            ],
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "RequestPath like '%/api/health'"
                }
              }
            ]
          }
        }
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "MinimumLevel": "Debug",
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "log\\SampleMy-.txt", //Write some log in different file. Control through code 
                  "rollingInterval": "Day",
                  "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [CorrId:{CorrelationId}] [Op:{OperationId}] [U:{UserName}] {Message:lj}{NewLine}{Exception}"
                }
              }
            ],
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "SourceContext = 'MyProject.IMyLogger'"
                }
              }
            ]
          }
        }
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "MinimumLevel": "Information",
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "log\\Sample-.txt", //all logs, without health-check
                  "rollingInterval": "Day",
                  "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [CorrId:{CorrelationId}] [Op:{OperationId}] [U:{UserName}] {Message:lj}{NewLine}{Exception}"
                }
              }
            ],
            "Filter": [
              {
                "Name": "ByExcluding",
                "Args": {
                  "expression": "RequestPath like '%/api/health'"
                }
              }
            ]
          }
        }
      }
    ],
    "Enrich": [
      "WithProcessName"
    ],
    "Properties": {
      "Application": "Sample",
      "Environment": "Test"
    }
  }

public class MyCommandHandler : IRequestHandler<MyCommand, Unit>
{
    private readonly ILogger _myLogger;
    private static int _count;

    public MyCommandHandler()
    {
        _myLogger = Log.ForContext<IMyLogger>();
    }

    public async Task<Unit> Handle(MyCommand request, CancellationToken cancellationToken)
    {
        _count++;

        Log.Debug("MyCommandHandler Count call = {count}",_count ); //write sample.txt
        Log.Information("MyCommandHandler Count call = {count}",_count ); //write in sample.txt
        Log.Error("MyCommandHandler Count call = {count}",_count); //write in sample.txt

        _myLogger.Information("Log from IMyLogger", _count); //write in sample.txt and in sampleMy.txt

        return Unit.Value;
    }
}

答案 4 :(得分:0)

由于简单的Serilog文档和任何接收器而苦苦挣扎了几天,这终于对我有用,而无需创建任何单独的记录器:

"Serilog": {
    "Using": [ "Serilog.Sinks.Async" ],
    "MinimumLevel": "Verbose",
    "Enrich": [ "FromLogContext", "WithDemystifiedStackTraces" ],
    "WriteTo:Information": {
        "Name": "Async",
        "Args": {
            "Configure": [
                {
                    "Name": "RollingFile",
                    "Args": {
                        "RestrictedToMinimumLevel": "Information",
                        "Formatter": "FOOINC.API.Configuration.Logging.CustomRenderedCompactJsonFormatter, FOOINC.API.Configuration",
                        "PathFormat": "_logs\\info\\info-log.json"
                    }
                }
            ]
        }
    },
    "WriteTo:Error": {
        "Name": "Async",
        "Args": {
            "Configure": [
                {
                    "Name": "RollingFile",
                    "Args": {
                        "RestrictedToMinimumLevel": "Error",
                        "Formatter": "FOOINC.API.Configuration.Logging.CustomRenderedCompactJsonFormatter, FOOINC.API.Configuration",
                        "PathFormat": "_logs\\errors\\error-log.json"
                    }
                }
            ]
        }
    }
}

希望这可以帮助任何人!

相关问题