C#用log4net记录日志
1. 首先在nuget包管理器,安装log4net
2. 在Properties---Assemblyinfo.cs添加log4net日志参数
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
3. 项目--添加--新建项--应用程序配置文件,修改名字log4net.config,右击log4net.config,文件属性,将复制到输出目录改为如果较新则复制
log4net文件修改为
<?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"> <!--定义文件存放位置--> <file value="log\\"/> <appendToFile value="true"/> <rollingStyle value="Date"/> <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.txt'"/> <staticLogFileName value="false"/> <param name="MaxSizeRollBackups" value="100"/> <param name="Encoding" value="UTF-8" /> <layout type="log4net.Layout.PatternLayout"> <!--每条日志末尾的文字说明--> <!--输出格式--> <!--样例:2008-03-26 13:42:32,111 [10] INFO Log4NetDemo.MainClass [(null)] - info--> <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别: %-5level %n描述:%message%newline %n"/> </layout> </appender> <root> <level value="ALL"/> <!--文件形式记录日志--> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> </configuration>
4. 在项目中添加LogHelper类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Myprint { class LogHelper { public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo"); public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror"); public static void WriteLog(string info) { if (loginfo.IsInfoEnabled) { loginfo.Info(info); } } public static void WriteLog(string info, Exception ex) { if (logerror.IsErrorEnabled) { logerror.Error(info, ex); } } } }
5. 记录日志,使用
LogHelper.loginfo.Info();