public class LogHelper { static string strLogCOMPath = Directory.GetCurrentDirectory() + "\Log\" + DateTime.Now.ToString("yyyyMMdd") + "LogJH.txt"; static string strLogErrorPath = Directory.GetCurrentDirectory() + "\Log\" + DateTime.Now.ToString("yyyyMMdd") + "ErrorLog.txt"; /// <summary> /// 记录交互日志 /// </summary> /// <param name="strLogContent">要记录的内容</param> /// <param name="bWriteFirstLine">是否要添加第一行日志title</param> /// <param name="strConentTitle">title内容</param> public static void AddCOMLog(string strLogContent, bool bWriteFirstLine, string strConentTitle) { string time1; time1 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); if (!File.Exists(strLogCOMPath)) { using (FileStream fs = new FileStream(strLogCOMPath, FileMode.Create, FileAccess.Write)) { if (bWriteFirstLine) { StringBuilder sb1 = new StringBuilder(); sb1.Append("时间").Append(",").Append(strConentTitle).Append(",").Append(" "); string str = sb1.ToString(); byte[] buffer = Encoding.Default.GetBytes(str); fs.Write(buffer, 0, buffer.Length); } } } using (StreamWriter sw = new StreamWriter(strLogCOMPath, true, Encoding.Default)) { StringBuilder sb = new StringBuilder(); sb.Append(time1).Append(",").Append(strLogContent).Append(","); sw.WriteLine(sb); } } /// <summary> /// 记录错误日志 /// </summary> /// <param name="strLogContent">要记录的内容</param> /// <param name="bWriteFirstLine">是否要添加第一行日志title</param> /// <param name="strConentTitle">title内容</param> public static void AddErrorLog(string strLogContent, bool bWriteFirstLine, string strConentTitle) { string time1; time1 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); if (!File.Exists(strLogErrorPath)) { using (FileStream fs = new FileStream(strLogErrorPath, FileMode.Create, FileAccess.Write)) { if (bWriteFirstLine) { StringBuilder sb1 = new StringBuilder(); sb1.Append("时间").Append(",").Append(strConentTitle).Append(",").Append(" "); string str = sb1.ToString(); byte[] buffer = Encoding.Default.GetBytes(str); fs.Write(buffer, 0, buffer.Length); } } } using (StreamWriter sw = new StreamWriter(strLogErrorPath, true, Encoding.Default)) { StringBuilder sb = new StringBuilder(); sb.Append(time1).Append(",").Append(strLogContent).Append(","); sw.WriteLine(sb); } } static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo"); static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror"); static string isAddLog = System.Configuration.ConfigurationSettings.AppSettings.Get("isAddLog"); /// <summary> /// 仅向日志中增加信息 /// </summary> /// <param name="info"></param> public static void WriteLog(string info) { if (isAddLog == "0") return; if (loginfo.IsInfoEnabled) { loginfo.Info(info); } } /// <summary> /// 记录错误日志 /// </summary> /// <param name="ex">错误异常</param> /// <param name="info">异常信息</param> public static void WriteLog(Exception ex, string info) { if (logerror.IsErrorEnabled) { logerror.Error(info, ex); } } }
<?xml version="1.0" encoding="utf-8" ?> <configuration> <log4net> <!--错误日志类--> <logger name="logerror"> <!--日志类的名字--> <level value="ALL" /> <!--定义记录的日志级别--> <appender-ref ref="ErrorAppender" /> <!--记录到哪个介质中去--> </logger> <!--信息日志类--> <logger name="loginfo"> <level value="ALL" /> <appender-ref ref="InfoAppender" /> </logger> <!--错误日志附加介质--> <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender"> <!-- name属性指定其名称,type则是log4net.Appender命名空间的一个类的名称,意思是,指定使用哪种介质--> <param name="File" value="Log\LogError\" /> <!--日志输出到exe程序这个相对目录下--> <param name="AppendToFile" value="true" /> <!--输出的日志不会覆盖以前的信息--> <param name="MaxSizeRollBackups" value="100" /> <!--备份文件的个数--> <param name="MaxFileSize" value="10240" /> <!--当个日志文件的最大大小--> <param name="StaticLogFileName" value="false" /> <!--是否使用静态文件名--> <param name="DatePattern" value="yyyyMMdd".html"" /> <!--日志文件名--> <param name="RollingStyle" value="Date" /> <!--文件创建的方式,这里是以Date方式创建--> <!--错误日志布局--> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="<HR COLOR=red>%n异常时间:%d [%t] <BR>%n异常级别:%-5p <BR>%n异 常 类:%c [%x] <BR>%n%m <BR>%n <HR Size=1>" /> </layout> </appender> <!--信息日志附加介质--> <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="Log\LogInfo\" /> <param name="AppendToFile" value="true" /> <param name="MaxFileSize" value="10240" /> <param name="MaxSizeRollBackups" value="100" /> <param name="StaticLogFileName" value="false" /> <param name="DatePattern" value="yyyyMMdd".html"" /> <param name="RollingStyle" value="Date" /> <!--信息日志布局--> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="<HR COLOR=blue>%n日志时间:%d [%t] <BR>%n日志级别:%-5p <BR>%n日 志 类:%c [%x] <BR>%n%m <BR>%n <HR Size=1>" /> </layout> </appender> </log4net> </configuration>
引用添加Log4net.DLL。
捕捉异常后,调用WriteLog方法,记录日志。
try { 代码块 } catch (Exception ex) { LogHelper.WriteLog(ex, ex.Message.ToString()); }
使用日志时,注意2点
1.目标框架不能使用Client Profile,否则无法找到Log4net.DLL。
2.在LogHelper的Project中Assembly程序集需要添加以下代码,否则无法写日志。
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]//让程序启动时是找到Log4net.config配置文件