public class MyLogger { public static void Log(string str) { StreamWriter sw = null; try { DirectoryInfo di = new DirectoryInfo(@"D:\testing");//获取D:\testing 目录的信息 if (!di.Exists)//如果没有该目录,则直接创建一个 { di.Create(); } FileInfo fileInfo = new FileInfo(@"D:\testing\test.txt");//获取 D:\testing\test.txt 文本的信息 if (!fileInfo.Exists)//同样的,如果没有该文件,则直接创建一个,注意使用CreateText创建完同时返回 StreamWriter 流 { sw = fileInfo.CreateText(); } else { sw = fileInfo.AppendText(); //存在该文件,则对该文件流进行写入叠加操作(即不覆盖掉之前写的东西) } sw.WriteLine(str); sw.Flush(); //注意关闭文件流 sw.Close(); sw.Dispose(); } catch (Exception ex) { if (sw != null) { sw.Close(); sw.Flush(); sw = null; } } } }
调用
MyLogger.Log("tesing......");
把整个Exception类传递给一个方法
/// <summary> /// 写错误日志 /// </summary> /// <param name="objErr"></param> /// <param name="context"></param> public void WriteErrorLog(Exception objErr) { HttpContext context = HttpContext.Current; //Exception objErr = context.Server.GetLastError().GetBaseException(); string strError = string.Empty; strError += "用户IP:" + context.Request.UserHostAddress + "\r\n"; strError += "发生时间:" + System.DateTime.Now.ToString() + "\r\n"; strError += "发生异常页: " + context.Request.Url.ToString() + "\r\n"; strError += "异常信息: " + objErr.Message + "\r\n"; strError += "异常方法: " + objErr.TargetSite + "\r\n"; strError += "错误源:" + objErr.Source + "\r\n"; strError += "错误堆栈信息:" + objErr.StackTrace + "\r\n"; strError += "----------------------------------------------------------------------------------------------\r\n"; //独占方式,因为文件只能由一个进程写入. System.IO.StreamWriter writer = null; try { lock (this) { // 写入日志 string year = DateTime.Now.Year.ToString(), month = DateTime.Now.Month.ToString(); string filename = DateTime.Now.Day.ToString() + ".txt"; string path = context.Server.MapPath("~/Error/") + year + "/" + month; //如果目录不存在则创建 if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } System.IO.FileInfo file = new System.IO.FileInfo(path + "/" + filename); writer = new System.IO.StreamWriter(file.FullName, true);//文件不存在就创建,true表示追加 writer.Write(strError); } } catch { context.Response.Redirect("~/Error.html"); } finally { if (writer != null) { writer.Flush(); writer.Close(); } } }
建议:
如非必要,Logger不要自己写,用Nlog或者log4net等第三方成熟控件。