木子宜居

导航

C#日志记录函数

错误日志记录在程序运行的实际维护中定位问题具有很大作用,日志越详细,反馈处理问题越方便。

常用的一个B/S架构下的日志函数。

//日志记录函数
private void WriteLog( string msgInfo)
{

     try

{
      string fileName = System.Web.HttpContext.Current.Server.MapPath("~/"); // System.Environment.CurrentDirectory;

if (fileName.Substring(fileName.Length - 1, 1) != "\\")
fileName = fileName + "\\";
fileName += "App_Data\\";
fileName += "Logs";

if (!Directory.Exists(fileName))
Directory.CreateDirectory(fileName);

fileName += "\\" + DateTime.Now.ToString("yyyyMMdd") + ".Log";


//-- 标识
string strType = "";
strType = "[ERR]";
//-- 时间
string strTime = "[" + DateTime.Now.ToString("HH:mm:ss:fff") + "]";

if (msgInfo == null) msgInfo = "NULL";
string strData = strType + strTime + msgInfo + "\r\n";

     System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName, true, System.Text.Encoding.Unicode);
     sw.Write(strData);
    sw.Close();

}
catch
{
}

}

记录例子如下:

[ERR][09:34:00:328]ExecuteReader 要求已打开且可用的连接。连接的当前状态为打开。

posted on 2015-04-22 10:01  木子宜居  阅读(908)  评论(0编辑  收藏  举报