Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

c# - Injecting NLog with Autofac's RegisterGeneric

Note: Updated with suggested improvements, closer but still not quite there!

Similar to this question - Passing in the type of the declaring class for NLog using Autofac - I am trying to inject NLog instances into my repository classes.

Interface:

public interface ILogger<T>
    where T: class
{
    ...
}

Implementation:

public class NLogger<T> : ILogger<T>
    where T: class
{
    private readonly Logger _logger;

    public NLogger()
    {
        _logger = LogManager.GetLogger(typeof(T).FullName);
    }

    public void Debug(string message)
    {
        _logger.Debug(message);
    }

    ...
}

Registered with Autofac as:

builder.RegisterGeneric(typeof (NLogger<>)).As(typeof (ILogger<>));

Using breakpoints, I see that Autofac is creating a bunch of ILogger/NLogger's with the correct types for all of my various repositories, but the resulting logs show up with callsite being "NLog.LoggerImpl.Write".

Thanks for any help!


Working solution with generics:

public class NLogger<T> : ILogger<T>
    where T: class
{
    private readonly Logger _logger;

    public NLogger()
    {
        _logger = LogManager.GetLogger(typeof(T).FullName);
    }

    public void Debug(string message)
    {
        _logger.Log(typeof(T), new LogEventInfo(LogLevel.Debug, _logger.Name, message));
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Logger wrappers need to call .Log() and pass additional info for callsite to work. For example:

_logger.Log(typeof (NLogger<T>), new LogEventInfo(LogLevel.Debug, _logger.Name, null, format, args));

EDIT: Since you're still having trouble, here's how I do it, and I know it's behaving correctly:

public interface ILog
{
    [StringFormatMethodAttribute("format")]
    void Debug(string format, params object[] args);
    [StringFormatMethodAttribute("format")]
    void Info(string format, params object[] args);
    [StringFormatMethodAttribute("format")]
    void Warn(string format, params object[] args);

    [StringFormatMethodAttribute("format")] 
    void Error(string format, params object[] args);
    void Error(Exception ex);

    [StringFormatMethodAttribute("format")]
    void Error(Exception ex, string format, params object[] args);

    [StringFormatMethodAttribute("format")]
    void Fatal(Exception ex, string format, params object[] args);
}

public class NLogLogger : ILog
{
    private readonly Logger _log;

    public NLogLogger(Type type)
    {
        _log = LogManager.GetLogger(type.FullName);
    }

    public void Debug(string format, params object[] args)
    {
        Log(LogLevel.Debug, format, args);
    }

    public void Info(string format, params object[] args)
    {
        Log(LogLevel.Info, format, args);
    }

    public void Warn(string format, params object[] args)
    {
        Log(LogLevel.Warn, format, args);
    }

    public void Error(string format, params object[] args)
    {
        Log(LogLevel.Error, format, args);
    }

    public void Error(Exception ex)
    {
        Log(LogLevel.Error, null, null, ex);
    }

    public void Error(Exception ex, string format, params object[] args)
    {
        Log(LogLevel.Error, format, args, ex);
    }

    public void Fatal(Exception ex, string format, params object[] args)
    {
        Log(LogLevel.Fatal, format, args, ex);
    }

    private void Log(LogLevel level, string format, object[] args)
    {
        _log.Log(typeof (NLogLogger), new LogEventInfo(level, _log.Name, null, format, args));
    }

    private void Log(LogLevel level, string format, object[] args, Exception ex)
    {
        _log.Log(typeof (NLogLogger), new LogEventInfo(level, _log.Name, null, format, args, ex));
    }
}

public class LoggingModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder
            .Register((c, p) => new NLogLogger(p.TypedAs<Type>()))
            .AsImplementedInterfaces();
    }

    protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
    {
        registration.Preparing +=
            (sender, args) =>
            {
                var forType = args.Component.Activator.LimitType;

                var logParameter = new ResolvedParameter(
                    (p, c) => p.ParameterType == typeof(ILog),
                    (p, c) => c.Resolve<ILog>(TypedParameter.From(forType)));

                args.Parameters = args.Parameters.Union(new[] { logParameter });
            };
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...