1、首先安装 log4net。
2、新建 log4net.config 文件,右键-属性 “复制到输出目录”设置为“始终复制”
3、设置 log4net.config 配置文件
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <!--日志记录组建配置--> <log4net> <!-- Console部分log输出格式的设定 --> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger %ndc - %message%newline" /> </layout> </appender> <!-- 日志文件部分log输出格式的设定 --> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--<file value="D:/log4netfile.txt" 日志的输出目录/>--> <file value="LogsLog_" /> <appendToFile value="true" /> <rollingStyle value="Date" /> <datePattern value="yyyyMMdd'.txt'" /> <staticLogFileName value="false" /> <layout type="log4net.Layout.PatternLayout"> <param name="Header" value=""/> <param name="Footer" value=""/> <param name="ConversionPattern" value="%n%d [%t] %-5p %c [%x] - %m" /> </layout> </appender> <!-- Setup the root category, add the appenders and set the default level --> <root> <level value="ALL" /> <appender-ref ref="ConsoleAppender" /> <appender-ref ref="RollingLogFileAppender" /> </root> </log4net> </configuration>
4、指定log4net使用.config文件来读取配置信息,写在类的命名空间前面或者
// ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); [assembly: log4net.Config.XmlConfigurator(ConfigFile = @"log4net.config", Watch = true)]
5、记录 log 信息
internal class SubsidyItem { ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static readonly SIMPEntities SIMP = new SIMPEntities(); /// <summary> /// 添加每月的驻外记录 /// </summary> public void AddSubsidyItem() { //当前时间 DateTime Date = DateTime.Now; //当前时间的上个月 DateTime LastDate = Date.AddMonths(-1); log.Info("当前插入统计信息的时间为:" + Date.Date.ToString("yyyy-MM-dd HH:mm:ss")); } }