Why have named logger in Log4Net?

和自甴很熟 提交于 2019-11-29 11:06:59

The recommended way to DI an Log4Net Log using Castle Windsor is to use Facilities. One has already been created for Log4Net and its use is demonstrated in this tutorial.

Good questions.

In short, log4net wants named loggers because then the names are used for filtering the log output (see the log4net documentation for details). Type name is just a convenient convention as it provides you that extra bit of context and coupled with correct use of namespaces allows you do things like say "log all NHibernate messages to a separate file"

That's also why commonly, if you're not using container for that, you have a single, static logger property/field in your classes.

The ILogger you're referring to is the abstraction in Castle over logging, one of which can be for log4net.

While the LoggingFacility provides out of the box support for providing dependencies on ILogger it is by no means forcing you to do this.

Your ILog registration should be rewritten as follows (I'm writing this from memory so details may be slightly different):

Component.For<log4net.ILog>()
    .UsingFactoryMethod((k, c) => log4net.LogManager.GetLogger(c.RequestedType))
    .LifestyleTransient()

c.RequestedType will give you the type for which you're satisfying the dependency and making it transient will avoid the issue that all types would reuse the single instance of logger named after whatever the first type to request the dependency was.

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