第一步:Log4net的安装
Install-Package log4net
第二步:Log4net的配置
log4net.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--日志路径--> <param name= "File" value= "sysLog\"/> <!--是否是向文件中追加日志--> <param name= "AppendToFile" value= "true"/> <!--log保留天数--> <param name= "MaxSizeRollBackups" value= "10"/> <!--日志文件名是否是固定不变的--> <param name= "StaticLogFileName" value= "false"/> <!--日志文件名格式为:2008-08-31.log--> <datePattern value="yyyy\yyyyMM\yyyyMMdd'.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> </configuration>
第三步:创建LogHelper类
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; [assembly: log4net.Config.XmlConfigurator(Watch = true)] namespace KongJiaCommon { public class LogHelper { /// <summary> /// 输出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="ex"></param> #region static void WriteLog(Type t, Exception ex) public static void WriteLog(Type t, Exception ex) { InitLog4Net(); log4net.ILog log = log4net.LogManager.GetLogger(t); log.Error("Error", ex); } #endregion /// <summary> /// 输出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="msg"></param> #region static void WriteLog(Type t, string msg) public static void WriteLog(Type t, string msg) { InitLog4Net(); log4net.ILog log = log4net.LogManager.GetLogger(t); log.Error(msg); } #endregion private static void InitLog4Net() { var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); log4net.Config.XmlConfigurator.ConfigureAndWatch(logCfg); } } }