NLog 在使用 ILoggerFactory / ILoggingBuilder 时设置自定义记录器命名空间后缀

NLog set custom logger namespace suffix when using ILoggerFactory / ILoggingBuilder

我有一个第三方库,让我有机会通过 ILoggerFactory 接口连接 NLog。 但是,我想为记录器命名空间添加一个后缀。

以下ExtensionMethod目前用于注入NLog.

var factory = LoggerFactory.Create(builder => builder.AddNLog());

目前,命名空间如下所示:

my.custom.library.class1

my.custom.library.class2

my.custom.library.with.inner.subclass

但是,我希望每个命名空间后面都有例如foo

my.custom.library.class1.foo

my.custom.library.class2.foo

my.custom.library.with.inner.subclass.foo

这是一个没有任何重载的快速修复。

var factory = LoggerFactory.Create(builder => builder.AddNLogWithSuffix(_IpSuffix));
public static class LoggingBuilderExtensions
{
    public static void AddNLogWithSuffix(this ILoggingBuilder builder, string loggerSuffix)
    {
        builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, NLogLoggerProviderWithSuffix>(_ => new NLogLoggerProviderWithSuffix(new NLogProviderOptions(), LogManager.LogFactory, loggerSuffix)));
    }
}

[ProviderAlias("NLog")]
public class NLogLoggerProviderWithSuffix : ILoggerProvider
{
    private readonly NLogLoggerProvider _NLogLoggerProvider;

    private readonly string _LoggerSuffix;

    /// <summary>New provider with options and a suffix</summary>
    /// <param name="options"></param>
    /// <param name="logFactory">Optional isolated NLog LogFactory</param>
    /// <param name="loggerSuffix"></param>
    public NLogLoggerProviderWithSuffix(NLogProviderOptions options, LogFactory logFactory, string loggerSuffix)
    {
        _LoggerSuffix = loggerSuffix;
        _NLogLoggerProvider = new NLogLoggerProvider(options, logFactory);
    }

    public void Dispose()
    {
        _NLogLoggerProvider.Dispose();
    }

    public ILogger CreateLogger(string categoryName)
    {
        return _NLogLoggerProvider.CreateLogger($"{categoryName}.{_LoggerSuffix}");
    }
}