在服务器上记录错误日志

using System.IO;

public class DebugLog
{
    public DebugLog()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

 

/// <summary>
  /// 根据日志的主文件名创建日志 
  /// </summary>
  /// <param name="CreateTime">创建日志的时间</param>
  /// <param name="Body">日志内容主体</param>
  /// <param name="FILE_PREFIX">文件名的关键主体</param>
    public static void WriteLog(DateTime CreateTime, string Body,string FILE_PREFIX)
    {
        try
        {
            lock (typeof(DebugLog))
            {
                string strLogPath = string.Empty;
                strLogPath = ConfigurationManager.AppSettings["LogPath"].ToString();
                if (string.IsNullOrEmpty(strLogPath))
                {
                    return;
                }

                //根据当天日期得出当天日志的文件名
                string strLogFileName = strLogPath + FILE_PREFIX + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                StreamWriter logWriter = null;

                //判断日志文件是否存在,存在则续行,不存在则创建并书写标题
                if (File.Exists(strLogFileName))
                {

                    logWriter = File.AppendText(strLogFileName);
                }
                else
                {
                    //创建文件
                    logWriter = File.CreateText(strLogFileName);

                }

                string strLogContent = string.Empty;
                string strLogId = string.Empty;
                strLogId = DateTime.Now.Ticks.ToString();
                strLogContent = "------------------------------------------------------------------------" + "\r\n";
                strLogContent = CreateTime + "\t" + "\r\n" + Body;
                strLogContent = strLogContent + "\r\n" + "------------------------------------------------------------------------";
                logWriter.WriteLine(strLogContent);
                logWriter.Close();
            }
        }
        catch { }
    }

}

posted @ 2009-06-19 16:02  张倩  阅读(1500)  评论(1编辑  收藏  举报