版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!
恰饭广告
环境:Nuget下载并安装log4net不在详细赘述
日志帮助类
public class LogHelper { /// <summary> /// 信息日志 /// </summary> /// <param name="type">当前实例</param> /// <param name="message">日志内容</param> /// <param name="exception">异常信息</param> public static void Info(Type type, object message, Exception exception = null) { ILog log = LogManager.GetLogger(type); if (exception == null) log.Info(message); else log.Info(message, exception); } /// <summary> /// 错误日志 /// </summary> /// <param name="type">当前实例</param> /// <param name="message">日志内容</param> /// <param name="exception">异常信息</param> public static void Error(Type type, object message, Exception exception = null) { ILog log = LogManager.GetLogger(type); if (exception == null) log.Error(message); else log.Error(message, exception); } }
Web.config配置(也可以是自己新建的config)
在configuration标签内加入
<log4net> <appender name="errorAppender" type="log4net.Appender.RollingFileAppender"> <param name="Encoding" value="utf-8" /> <!--日志编码--> <filter type="log4net.Filter.LevelMatchFilter"> <levelToMatch value="ERROR" /> <!--日志类型--> </filter> <filter type="log4net.Filter.DenyAllFilter" /> <File value="Logs\LogError\" /> <!--日志路径--> <appendToFile value="true" /> <rollingStyle value="Date" /> <datePattern value="yyyyMMdd".log"" /> <!--日志文件名称(按日期记录)--> <StaticLogFileName value="false" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> <appender name="infoAppender" type="log4net.Appender.RollingFileAppender"> <param name="Encoding" value="utf-8" /> <filter type="log4net.Filter.LevelMatchFilter"> <levelToMatch value="INFO" /> </filter> <filter type="log4net.Filter.DenyAllFilter" /> <File value="Logs\LogInfo\" /> <appendToFile value="true" /> <rollingStyle value="Date" /> <datePattern value="yyyyMMdd".log"" /> <StaticLogFileName value="false" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> <root> <level value="ALL" /> <appender-ref ref="errorAppender" /> <appender-ref ref="infoAppender" /> </root> </log4net>
AssemblyInfo.cs配置(安装log4net默认就有 不用新建)
底部加入
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", ConfigFileExtension = "config", Watch = true)]
注意:ConfigFile可以指定新建的config名称
使用方法:
try { ///正常代码写入 LogHelper.Info(this.GetType(), "admin-登录"); } catch(Exception ex) { ///异常代码写入 LogHelper.Error(this.GetType(), ex); }
效果查看:项目根目录下Logs文件夹里
原文链接:https://www.idaobin.com/archives/2049.html
让我恰个饭吧.ヘ( ̄ω ̄ヘ)
恰饭广告