C# 利用Log4net记录日志简单实例
一、安装Log4net程序包
参考:https://www.cnblogs.com/weixiaowei/p/8253228.html
二、在项目中引用Log4net的dll文件
三、配置config文件
<log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--日志路径--> <param name="File" type="log4net.Util.PatternString" value="%Log\%date{yyyMMdd}.log" /> <!--是否是向文件中追加日志--> <param name="AppendToFile" value="true" /> <!--log保留天数--> <param name="MaxSizeRollBackups" value="10" /> <!--日志文件名是否是固定不变的--> <param name="StaticLogFileName" value="false" /> <!--日志文件名格式为:2008-08-31.log--> <param name="DatePattern" value="yyyy-MM-dd".log"" /> <!--日志根据日期滚动--> <param name="RollingStyle" value="Date" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" /> </layout> </appender> <!-- 控制台前台显示日志 --> <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender"> <mapping> <level value="ERROR" /> <foreColor value="Red, HighIntensity" /> </mapping> <mapping> <level value="Info" /> <foreColor value="Green" /> </mapping> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="Info" /> <param name="LevelMax" value="Fatal" /> </filter> </appender> <root> <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) --> <level value="all" /> <appender-ref ref="ColoredConsoleAppender" /> <appender-ref ref="RollingLogFileAppender" /> </root> </log4net>
四、后台添加
using log4net.Config; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RM.Utilities { public static class LogManager { private static ILog loger = new MDLog(); public static void Debug(string s) { loger.Debug(s); } public static void Error(string s) { loger.Error(s); } public static void Fatal(string s) { loger.Fatal(s); } public static void Info(string s) { loger.Info(s); } } public interface ILog { void Debug(string s); void Error(string s); void Fatal(string s); void Info(string s); } public class MDLog : ILog { public MDLog() { XmlConfigurator.Configure(); } private log4net.ILog loger = log4net.LogManager.GetLogger("RM.RealtimeMonitoring"); public void Debug(string s) { loger.Debug(s); } public void Error(string s) { loger.Error(s); } public void Fatal(string s) { loger.Fatal(s); } public void Info(string s) { loger.Info(s); } } }
五、调用
LogManager.Debug(classid.ToString());
六、参考