我想使用Serilog.Expressions
来过滤特定接收器的日志记录。在这种情况下,如果我的自定义属性MethodName
等于"SomeOtherTask“,我只想登录到控制台Sink。Serilog仍在为DoSomeWork
和SomeOtherTask
登录到Sinks。我的过滤器表达式有什么问题吗?或者我是如何实现我的自定义属性MethodName
或其他什么的?
appsettings.json:
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Expressions" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "Console",
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "MethodName = 'SomeOtherTask'"
}
}
]
},
{
"Name": "File",
"Args": {
"path": "Logs/log.txt"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "SerilogSplitLogTest"
}
}
}
Program.cs:
internal class Program
{
static void Main()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true);
var config = builder.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger();
new Program().Run(logger);
Console.ReadKey(true);
}
public void Run(ILogger logger)
{
DoSomeWork(logger);
SomeOtherTask(logger);
}
public void DoSomeWork(ILogger logger)
{
logger.Information("This should log to File");
}
public void SomeOtherTask(ILogger logger)
{
using (LogContext.PushProperty("MethodName", nameof(SomeOtherTask)))
{
logger.Information("This should log to Console");
}
}
}
发布于 2022-06-27 10:53:45
我有类似的问题,写到两个文件,一个是拥有所有的日志,而在那里,其他是由一个属性过滤,所以它是一种压缩日志。我就是这么做的。
首先,确保安装Serilog.Expressions。单独这样做可能会解决您的问题,如果没有,下面是我使用的配置的WriteTo部分。
注意:Marker
是我正在筛选的自定义属性。
"WriteTo": [
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "Marker is not null"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "D:\\Temp\\SerilogTesting.txt",
"outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] - [{Level:u3}] - [{SourceContext}.{Method}] - {Message:lj}{NewLine:1}{Exception:1}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7,
"shared": true
}
}
]
}
}
},
{
"Name": "File",
"Args": {
"path": "D:\\Temp\\SerilogTesting.log",
"outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] - [{Level:u3}] - [{SourceContext}.{Method}] - {Message:lj}{NewLine:1}{Exception:1}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7,
"shared": true
}
},
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
"outputTemplate": "[{Marker}][{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] - [{Level:u3}] - [{SourceContext}.{Method}] - {Message:lj}{NewLine:1}{Exception:1}"
}
}
]
然后我的财产就这样被推下去了
_logger.ForContext("Marker","LW").Information("Something to log");
https://stackoverflow.com/questions/71582077
复制相似问题