編寫操作日誌類的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace Discuz.WebService
{
    public class LogWrite
    {
        private string filePath = null;
        public LogWrite()
        {
            try
            {
                string Dir = HttpContext.Current.Server.MapPath("~/Log/");
                if (!Directory.Exists(Dir))
                {
                    Directory.CreateDirectory(Dir);
                }
                filePath = Dir + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
            }
            catch (Exception) { }
        }
        /// <summary>
        /// 寫入錯誤信息
        /// </summary>
        /// <param name="ex"></param>
        public void WriteLog(Exception ex, string IP)
        {
            using (StreamWriter sw = new StreamWriter(filePath, true, System.Text.Encoding.UTF8))
            {
                sw.WriteLine(string.Format("時間:{0} 錯誤原因:{1}", DateTime.Now.ToString(), ex.Message));
                sw.WriteLine(string.Format("用戶IP:{0}", IP));
                sw.WriteLine("錯誤信息:");
                sw.WriteLine(ex.StackTrace);
                sw.WriteLine("-----------------------------------------------------------------------------------------------");
                sw.WriteLine("");
                sw.Flush();
                sw.Close();
            }
        }
        /// <summary>
        /// 寫入錯誤信息
        /// </summary>
        /// <param name="ex"></param>
        public void WriteLog(string msg, string IP)
        {
            using (StreamWriter sw = new StreamWriter(filePath, true, System.Text.Encoding.UTF8))
            {
                sw.WriteLine(string.Format("時間:{0} 錯誤原因:{1}", DateTime.Now.ToString(), msg));
                sw.WriteLine(string.Format("用戶IP:{0}", IP));
                sw.WriteLine("-----------------------------------------------------------------------------------------------");
                sw.WriteLine("");
                sw.Flush();
                sw.Close();
            }
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章