Using log4net with Autofac

匿名 (未验证) 提交于 2019-12-03 01:08:02

问题:

I am trying to use log4net with Autofac. I've pasted this code http://autofac.readthedocs.org/en/latest/examples/log4net.html , and from Program.cs/Main() I am doing

var iocBuilder = new ContainerBuilder(); iocBuilder.RegisterModule(new LoggingModule()); var iocContainer = iocBuilder.Build(); 

now I would like to try this out immediately (in the next line), writing a simple line to the log file. How should I do it?

I am thinking of something like this

var ls = iocContainer.Resolve<LoggingModule>(); ls.Info("the logging is working"); 

Thanks a lot

回答1:

To obtain a ILog, log4net need to know the class that use the logger (LogManager.GetLogger(...)). So, you can't resolve a ILog without a parent class. You have to inject the ILog inside a component.

public class MyComponent {      public MyComponent(ILog logger)      {           this._logger = logger;       }       private readonly ILog _logger;        public void Do()      {            this._logger.Info("Log4net OK");      } }  // ... log4net.Config.XmlConfigurator.Configure(); // ... iocBuilder.RegisterModule(new LoggingModule()); iocBuilder.RegisterType<MyComponent>().AsSelf();   // ...  MyComponent c = iocContainer.Resolve<MyComponent>(); c.Do();  

Another solution would be to register an ILog for Object and resolve ILog. In this case, the module is not required.

log4net.Config.XmlConfigurator.Configure(); /// ... ContainerBuilder cb = new ContainerBuilder() cb.Register(c => LogManager.GetLogger(typeof(Object))).As<ILog>(); IContainer container = cb.Build();   ILog logger = container.Resolve<ILog>(); logger.Info("log4net OK");  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!