C#创建日志通用类<包含log4net日志和特殊日志(年/月/日/文件名.log)>
2012-03-28 09:30:06 来源:WEB开发网核心提示:public class LogerHelper { public LogerHelper() { SetConfig(); } private static ILog loginfo = LogManager.GetLogger( &
public class LogerHelper { public LogerHelper() { SetConfig(); } private static ILog loginfo = LogManager.GetLogger( "myLogger" ); private static void SetConfig() { log4net.Config.XmlConfigurator.ConfigureAndWatch( new System.IO.FileInfo( "Configs/Log4net.xml" ) ); } private static bool IsLoadConfig = false; /// <summary> /// 记录日志 /// </summary> /// <param name="info">提示信息</param> public static void WriteLog( string info ) { if (!IsLoadConfig) { SetConfig(); IsLoadConfig = true; } if (loginfo.IsInfoEnabled) { loginfo.Info( info ); } } /// <summary> /// 记录异常 /// </summary> /// <param name="info">错误</param> /// <param name="ex">Exception</param> public static void WriteLog( string info, Exception ex ) { if (!IsLoadConfig) { SetConfig(); IsLoadConfig = true; } if (loginfo.IsErrorEnabled) { loginfo.Error( info, ex ); } } /// <summary> /// 一天一个日志 /// 生成方式:目录:Error/年/月/日/文件名.log /// </summary> /// <param name="message"></param> public static void LogToFile( string message ) { try { DirectoryInfo dir; //修改记录日志为C盘根目录,并且注释判断当前程序目录内是否存在log日志文件夹 if (!Directory.Exists( "Error" )) { dir = Directory.CreateDirectory( "Error" ); dir.Create(); } else { if (!Directory.Exists( @"Error/" + DateTime.Today.Year.ToString() + "/" + DateTime.Today.Month.ToString() + "/" + DateTime.Today.Day.ToString() )) { Directory.CreateDirectory( @"Error/" + DateTime.Today.Year.ToString() + "/" + DateTime.Today.Month.ToString() + "/" + DateTime.Today.Day.ToString() ); } } using (StreamWriter writer = new StreamWriter( @"Error/" + DateTime.Today.Year.ToString() + "/" + DateTime.Today.Month.ToString() + "/" + DateTime.Today.Day.ToString() + "/更新的接警单编号.log", true )) { try { writer.Write( "时间:\t" + DateTime.Now.ToString() + "\t \t \t \t" ); writer.WriteLine( message ); //writer.WriteLine( Environment.NewLine ); writer.Flush(); writer.Close(); } catch (Exception exec) { WriteLog( "写入错误", exec ); writer.Dispose(); } } } catch (Exception ex) { WriteLog( "创建错误", ex ); } } } //用的方法如下: LogerHelper.LogToFile( "创建日志"); //这个将生成诸如这样的Error/年/月/日/文件名.log的日志LogerHelper.WriteLog("单独的日志"); //这个将写入到Error/log.log文件夹下,只记录一个单独的infoLogerHelper.WriteLog("单独的日志",ex); //这个也将写入到Error/log.log文件夹下,记录单独的info,和一个异常信息//注意:此方法在winform里边是不用配置log4net的节点的,可以将附件中的log4net.xml放入到winform下的configs(若没有需要自己建立)下面,然后将这个xml的生成操作属性改为嵌入的资源 和 复制到输出目录改为:如果较新则复制<br><br><br>
更多精彩
赞助商链接