.net 5.0 下记录日志以及日志的配置
1.我们先开始准备一个日志的Helper
2.然后在指定目录下添加配置文件 .XML
using log4net; using log4net.Config; using System; using System.IO; namespace AnnualBill.Logger { public class LoggerHelper { #region Fields private static readonly ILog logger; #endregion #region Constructors static LoggerHelper() { if (logger == null) { var repository = LogManager.CreateRepository("MixdoRepository"); //log4net从log4net.config文件中读取配置信息 var log4netConfig = new FileInfo("App_Data/log4net.config.xml"); XmlConfigurator.Configure(repository, log4netConfig); logger = LogManager.GetLogger(repository.Name, "InfoLogger"); } } #endregion #region Utilities /// <summary> /// 普通日志 /// </summary> /// <param name="message"></param> /// <param name="exception"></param> public static void Info(string message, Exception exception = null) { if (exception == null) logger.Info(message); else logger.Info(message, exception); } /// <summary> /// 告警日志 /// </summary> /// <param name="message"></param> /// <param name="exception"></param> public static void Warn(string message, Exception exception = null) { if (exception == null) logger.Warn(message); else logger.Warn(message, exception); } /// <summary> /// 错误日志 /// </summary> /// <param name="message"></param> /// <param name="exception"></param> public static void Error(string message, Exception exception = null) { if (exception == null) logger.Error(message); else logger.Error(message, exception); } #endregion } }
<?xml version="1.0" encoding="utf-8"?> <log4net> <!-- Define some output appenders --> <appender name="rollingAppender" type="log4net.Appender.RollingFileAppender"> <file value="log.txt" /> <!--追加日志内容--> <appendToFile value="true" /> <!--防止多线程时不能写Log--> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <!--可以为:Once|Size|Date|Composite--> <!--Composite为Size和Date的组合--> <rollingStyle value="Composite" /> <!--当备份文件时,为文件名加的后缀--> <datePattern value="yyyyMMdd.TXT" /> <!--日志最大个数,都是最新的--> <!--rollingStyle节点为Size时,只能有value个日志--> <!--rollingStyle节点为Composite时,每天有value个日志--> <maxSizeRollBackups value="20" /> <!--可用的单位:KB|MB|GB--> <maximumFileSize value="3MB" /> <!--置为true,当前最新日志文件名永远为file节中的名字--> <staticLogFileName value="true" /> <!--输出级别在INFO和ERROR之间的日志--> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="ALL" /> <param name="LevelMax" value="FATAL" /> </filter> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/> </layout> </appender> <root> <priority value="ALL"/> <level value="ALL"/> <appender-ref ref="rollingAppender" /> </root> </log4net>