我有一个 .NET Core 2.0 应用程序,我在其中成功使用 Serilog 进行日志记录。现在,我想将一些数据库性能统计信息记录到一个单独的接收器(它们不是为了调试,这基本上是应用程序中所有其他日志记录的目的,所以我想将它们分开)并认为这可以完成通过使用
Log.ForContext<MyClass>()
创建数据库统计记录器。
我不知道应该如何配置 Serilog 使用我的 appsettings.json 将我的“调试日志”记录到一个接收器并将我的数据库统计日志记录到另一个接收器?我希望可以做这样的事情:
"Serilog": {
"WriteTo": [
{
"Name": "RollingFile",
"pathFormat": "logs/Log-{Date}.log",
"Filter": {
"ByExcluding": "FromSource(MyClass)"
}
},
{
"Name": "RollingFile",
"pathFormat": "logs/DBStat-{Date}.log",
"Filter": {
"ByIncludingOnly": "FromSource(MyClass)"
}
}
]
}
配置的
"Filter"
部分纯粹是我的猜测。使用我的配置文件管理器可以做到这一点吗?或者我需要在我的 Startup.cs
文件中的代码中执行此操作吗?
编辑:我已经使用 C# API 让它工作了,但仍然想使用 JSON 配置来解决它:
Log.Logger = new LoggerConfiguration()
.WriteTo.Logger(lc => lc
.Filter.ByExcluding(Matching.FromSource<MyClass>())
.WriteTo.LiterateConsole())
.WriteTo.Logger(lc => lc
.Filter.ByExcluding(Matching.FromSource<MyClass>())
.WriteTo.RollingFile("logs/DebugLog-{Date}.log"))
.WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(Matching.FromSource<MyClass>())
.WriteTo.RollingFile("logs/DBStats-{Date}.log", outputTemplate: "{Message}{NewLine}"))
.CreateLogger();
我今天完成了这项工作,并认为我会提供一个正确的答案,因为我花了很多帖子、问题和其他页面来解决这个问题。
拥有所有日志很有用,但我也想仅单独记录我的 API 代码,并省略
Microsoft.
命名空间日志。执行此操作的 JSON 配置如下所示:
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "/var/logs/system.log",
... //other unrelated file config
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "/var/logs/api.log",
... //other unrelated file config
}
}
],
"Filter": [
{
"Name": "ByExcluding",
"Args": {
"expression": "StartsWith(SourceContext, 'Microsoft.')"
}
}
]
}
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
... //Destructure and other config
}
顶层
WriteTo
是第一个简单的全局接收器。所有日志事件都会写入此内容。如果您在与此相同的级别添加 Filter
部分,它将影响所有配置的 WriteTo
元素。
然后我将另一个
WriteTo
配置为 Logger
(不是 File
),但是 Args
看起来不同,并且有一个 configureLogger
元素,其用途与顶层的 Serilog
相同,也就是说,它是子记录器的顶层。这意味着您可以轻松地将其配置拆分为一个单独的文件,并将其另外添加到配置生成器中(见底部)。
从这里开始,这个子记录器的工作方式相同:您可以配置多个
WriteTo
,并且此级别上的 Filter
元素将仅影响此子记录器。
只需将更多
"Name": "Logger"
元素添加到顶级 WriteTo
部分,并分别为每个元素设置过滤器。
注意 同样重要的是要注意,即使您在配置中执行所有这些操作并且没有在代码中引用
Serilog.Expressions
包的任何一个位,您仍然需要添加对该包的 NuGet 引用。 没有包参考就无法工作。
关于拆分配置:
如果我必须添加更多记录器,为了清楚起见,我肯定会将不同的记录器分成单独的文件,例如
appsettings.json:
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Error",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "/var/logs/system.log",
...
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {} // leave this empty
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
...
apilogger.json:
{
"Serilog:WriteTo:1:Args:configureLogger": { //notice this key
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "/var/logs/api_separateFile.log",
...
}
}
],
"Filter": [
{
"Name": "ByExcluding",
"Args": {
"expression": "StartsWith(SourceContext, 'Microsoft.')"
}
}
]
}
}
然后调整我的
IWebHost
构建器以包含附加配置:
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("apilogger.json", optional: false, reloadOnChange: false);
})
.UseStartup<Startup>();
这样更容易理解、阅读和维护。
下面仅将实体框架日志写入文件,但我们需要安装 Serilog.Filters.Expressions nuget 包
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"System": "Warning",
"Microsoft.EntityFrameworkCore": "Information"
}
},
"WriteTo": [
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "StartsWith(SourceContext, 'Microsoft.EntityFrameworkCore')"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\LOGS\\TestService_EF_.json",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
]
}
}
}
]
}
我必须做类似的事情,但是用代码,而不是 JSON。使用记录器作为接收器,如 https://github.com/serilog/serilog/wiki/Configuration-Basics 底部所述,成功了。
就我而言,我想将所有内容记录到文件和控制台,除了来自特定源的消息应该只发送到文件:
private static bool SourceContextEquals(LogEvent logEvent, Type sourceContext)
=> logEvent.Properties.GetValueOrDefault("SourceContext") is ScalarValue sv && sv.Value?.ToString() == sourceContext.FullName;
private static ILogger CreateLogger() =>
new LoggerConfiguration()
.WriteTo.File("mylog.log")
.WriteTo.Logger(lc =>
lc.Filter.ByExcluding(le => SourceContextEquals(le, typeof(TypeThatShouldLogOnlyToFile)))
.WriteTo.Console()
)
.CreateLogger();
Serilog 还添加了在 C# 中设置选项的功能。例如:
.WriteTo.Console(
restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information)