NLog with AutoFac - How to give logger name
builder.RegisterGeneric(typeof(MyNLogger<>)).As(typeof(IMyLogger<>)); //泛型
增加一个泛型的IMyLogger接口, MyNLogger的泛型类
public interface IMyLogger<T> { void Debug(string message); void Info(string message); void Error(string message); void Fatal(string message); }
public class MyNLogger<T> : IMyLogger<T> { public ILogger logger { get; set; } public MyNLogger() { logger = LogManager.GetLogger(typeof(T).FullName); } public void Debug(string message) { logger.Debug(message); } public void Error(string message) { logger.Debug(message); } public void Fatal(string message) { logger.Fatal(message); } public void Info(string message) { logger.Info(message); } }
public class Temp { private IMyLogger<Temp> logger; public Temp() { } public Temp(IMyLogger<Temp> logger) { this.logger = logger; } public override bool testCom( { logger.Info(" testCom"); return ret; }
如何AOP在每个方法加上LOG呢? 2种方法,一种在类名写特性[Intercept(typeof(LogInterceptor))],另一种是builder.RegisterType<XXX>().EnableClassInterceptors().InterceptedBy(typeof(LogInterceptor)), 我倾向后一种, 因为EnableClassInterceptors你一定要写的,顺便再写一句InterceptedBy很自然,不用再去找类
class Program { private static IContainer Container { get; set; } static void Main(string[] args) { var builder = new ContainerBuilder(); builder.RegisterType<LogInterceptor>();// AOP IInterceptor必须先注册 builder.RegisterType<Temp_DM7210>() .EnableClassInterceptors() .InterceptedBy(typeof(LogInterceptor)) .As<ASerialDevice>(); builder.RegisterGeneric(typeof(MyNLogger<>)) .EnableInterfaceInterceptors() .As(typeof(IMyLogger<>)); //泛型 //var Logger = LogManager.GetLogger("ABC"); //builder.RegisterInstance(Logger).As<ILogger>();//从实例转成接口,这样构造函数里用ILogger的时候,就自动用这个实例化 Container = builder.Build(); ASerialDevice a= Container.Resolve<ASerialDevice>(); string msg = ""; a.testCom(ref msg); } }
/// <summary> /// 拦截器 引用Autofac.Extras.DynamicProxy,需要实现 IInterceptor接口 Intercept方法 /// </summary> public class LogInterceptor : IInterceptor { /// <summary> /// 拦截方法 打印被拦截的方法执行前的名称、参数和方法执行后的 返回结果 /// </summary> /// <param name="invocation">包含被拦截方法的信息</param> public void Intercept(IInvocation invocation) { Console.WriteLine("方法执行前:拦截{0}类下的方法{1}的参数是{2}", invocation.InvocationTarget.GetType(), invocation.Method.Name, string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())); //在被拦截的方法执行完毕后 继续执行 invocation.Proceed(); Console.WriteLine("方法执行完毕,返回结果:{0}", invocation.ReturnValue); Console.WriteLine(); } }