当前位置: 首页 > 编程语言 > C#

log4net'sloggerwrapper的实现和使用分享

时间:2023-04-10 19:40:43 C#

log4net'sloggerwrapper的实现和使用这个问题和Steven的回答相关-这里。他想出了一个非常好的记录器包装器。我将在下面粘贴他的代码:publicinterfaceILogger{voidLog(LogEntryentry);}publicstaticclassLoggerExtensions{publicstaticvoidLog(thisILoggerlogger,stringmessage){logger.Log(newLogEntry(LoggingEventType.Information,message,null));}publicstaticvoidLog(thisILoggerlogger,Exceptionexception){logger.Log(newLogEntry(LoggingEventType.Error,exception.Message,exception));}//这里有更多方法。所以,我的问题是为log4net实现创建代理的正确方法是什么?我应该只添加另一个带有类型参数的日志扩展方法并在其中创建一个开关吗?LoggingEventType的不同log4net方法?第二个问题,稍后在代码中使用它的最佳方法是什么?正如他所写:(...)您可以轻松地创建一个ILogger实现(...)并配置您的DI容器以将其注入到在构造函数中具有ILogger的类中。这是否意味着将记录的每个类(基本上每个类)都应该在其构造函数中使用ILogger?所以,我的问题是创建代理到log4net的实现的正确方法是什么?您应该创建如下内容:publicclassLog4netAdapter:ILogger{privatereadonlylog4net.ILogm_Adaptee;publicLog4netAdapter(log4net.ILogadaptee){m_Adaptee=adaptee;}publicvoidLog(LogEntryentry){//这里调用m_Adapteeif(entry.Severity==LoggingEventType.Debug)m_Adaptee.Debug(entry.Message,entry.Exception);elseif(entry.Severity==LoggingEventType.Information)m_Adaptee.Info(entry.Message,entry.Exception);elseif(entry.Severity==LoggingEventType.Warning)m_Adaptee.Warn(entry.Message,entry.Exception);elseif(entry.Severity==LoggingEventType.Error)m_Adaptee.Error(entry.Message,entry.Exception);否则m_Adaptee.Fatal(entry.Message,entry.Exception);这是否意味着每个将记录日志的类(基本上每个类)都应该在其构造函数中使用ILogger?正如我从史蒂文斯的回答中了解到的那样:是的,你应该。稍后在代码中使用它的最佳方法是什么?如果使用DI容器,只需要使用DI容器将ILogger映射到Log4netAdapter。您还需要注册log4net.ILog,或者简单地向DI容器提供一个log4net记录器实例,以将其注入到Log4netAdapter构造函数中。如果你不使用DI容器,即使用PureDI,那么你可以进行如下操作:以上是C#学习教程:log4netloggerwrapper的实现和使用。如果对大家有用,需要了解更多关于C#学习教程,希望大家多多关注——ILoglog=log4net.LogManager.GetLogger("MyClass");ILoggerlogging_adapter=newLog4netAdapter(日志);varmyobject=newMyClass(other_dependencies_here,logging_adapter);代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: