Serilog Filter.ByInIncluded Only not working namspace

问题描述 投票:0回答:1

我在我的dotnet 4.8应用程序中使用serilog(2.8)。请参阅有助于初始化serilog的代码。

    var isxyz = Matching.FromSource("xyz.Dispose");
    Log.Logger = new LoggerConfiguration()
    .Enrich.WithProperty("ServiceName", servicename)
    .Enrich.FromLogContext()
    .MinimumLevel.Debug()
    .Filter.ByIncludingOnly(i=> isxyz(i))
    .WriteTo.Console()

    .WriteTo.File(AppDomain.CurrentDomain.BaseDirectory + "Logs" + "\\" + "log-.txt", rollingInterval: RollingInterval.Day, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {ServiceName} {CountryCode} {Message:lj}{NewLine}{Exception}")
    .CreateLogger();

这里我仅包含名称空间xyz.Dispose。因此,在控制台和文件接收器中,我应该只从名称空间xyz.Dispose

中获取日志。

但是在配置上述设置之后,没有日志被打印到控制台或文件中。

c# serilog
1个回答
0
投票

您的过滤器在每条日志消息的SourceContext属性上都是匹配的,因此,如果没有日志消息写入日志中,则您要么not都在记录器中先设置SourceContext属性,然后再向其写入(最有可能)或您所设置的SourceContextxyz.Dispose有所不同,这将导致您的过滤器将邮件排除在写入范围之外。

设置SourceContext的方法有很多,但是一个简单的例子是:

var logger = Log.Logger.ForContext(Constants.SourceContextPropertyName, "xyz.Dispose");
logger.Information("This should appear in the log");

填充SourceContext属性的一种常见方法是在类中使用通用方法ForContext<T>。例如:

using Serilog;

namespace xyz.Dispose
{
    public class MyService
    {
        private readonly ILogger _log = Log.ForContext<MyService>();

        public void DoStuff()
        {
            _log.Information("This should appear in the log");

            // ...
        }
    }
}

在上面的示例中,SourceContext将自动使用类的全名(xyz.Dispose.MyService)填充,该类的名称与您的过滤器相匹配,因为它具有名称空间。


与您的问题无关:xyz.Dispose似乎不是名称空间的好名字... Dispose在任何.NET代码库中都是如此常见的方法,可能会引起混淆。也许使用描述一组事物的东西?例如Disposables

© www.soinside.com 2019 - 2024. All rights reserved.