C# 日志类

lock 关键字可确保当一个线程位于代码的临界区时,另一个线程不会进入该临界区。如果其他线程试图进入锁定的代码,则它将一直等待(即被阻止),直到该对象被释放。

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.IO;
namespace WriteLogClass
{
    /// <summary>
    /// 错误信息处理类
    /// </summary>
    public class Error
    {
        /// <summary>
        /// 对象
        /// </summary>
        public object obj = new object();
        /// <summary>
        /// 对象
        /// </summary>
        public static object Obj = new object();
        /// <summary>
        /// 错误信息中的错误信息
        /// </summary>
        private string ErrMessAge;
        /// <summary>
        /// 错误信息中的错误信息
        /// </summary>
        public string ErrMessage
        {
            get { return ErrMessAge; }
            set { ErrMessAge = value; }
        }
        /// <summary>
        /// 错误ID
        /// </summary>
        private string ErrId;
        /// <summary>
        /// 错误ID
        /// </summary>
        public string Id
        {
            get { return ErrId; }
            set { ErrId = value; }
        }
        /// <summary>
        /// 错误信息
        /// </summary>
        private string MessAge;
        /// <summary>
        /// 错误信息
        /// </summary>
        public string Message
        {
            get { return MessAge; }
            set { MessAge = value; }
        }
        /// <summary>
        /// 类名
        /// </summary>
        private string className;
        /// <summary>
        /// 类名
        /// </summary>
        public string ClassName
        {
            get { return className; }
            set { className = value; }
        }
        /// <summary>
        /// 方法名
        /// </summary>
        private string functionName;
        /// <summary>
        /// 方法名
        /// </summary>
        public string FunctionName
        {
            get { return functionName; }
            set { functionName = value; }
        }
        /// <summary>
        /// 错误源
        /// </summary>
        private string DataSource;
        /// <summary>
        /// 错误源
        /// </summary>
        public string Source
        {
            get { return DataSource; }
            set { DataSource = value; }
        }

        #region 把错误信息写入日志
        /// <summary>
        /// 把错误信息写入日志
        /// </summary>
        public void WriteLog()
        {
            lock (this.obj)
            {
                string Path = "";
                try
                {
                    Path = System.Configuration.ConfigurationManager.AppSettings["LogPath"].ToString();
                }
                catch (Exception e)
                {
                    Path = "/Log";
                    this.ErrMessAge = e.Message;
                }
                string p = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + Path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                Path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + Path;
                if (!Directory.Exists(Path))
                {
                    DirectoryInfo Dir = Directory.CreateDirectory(Path);
                    Dir.Refresh();
                }
                if (!File.Exists(p))
                {
                    FileStream fso = File.Create(p);
                    fso.Close();
                    fso.Dispose();

                    StreamWriter SW = File.AppendText(p);
                    SW.WriteLine("===================================================================================================");
                    SW.WriteLine("                           本站日志文件                          ");
                    SW.WriteLine("===================================================================================================");
                    SW.WriteLine("");
                    SW.Flush();
                    SW.Close();
                    SW.Dispose();
                }
                StreamWriter sw = File.AppendText(p);
                sw.WriteLine("");
                sw.WriteLine("===================================================================================================");
                sw.WriteLine("");
                sw.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]  ");
                sw.WriteLine("错误数据源:" + this.Source);
                sw.WriteLine("错误方法:");
                sw.WriteLine("错误方法所属类:" + this.ClassName);
                sw.WriteLine("错误方法:" + this.FunctionName);
                try
                {
                    sw.WriteLine("当前IP:" + XiaoFeng.Function.GetIP4Address() + "");
                    sw.WriteLine("当前错误页面地址:" + System.Web.HttpContext.Current.Request.Url.ToString());
                }
                catch (Exception ex) { }
                sw.WriteLine("当前错误信息:" + this.Message.ToString());
                sw.Flush();
                sw.Close();
                sw.Dispose();
            }
        }
        /// <summary>
        /// 写错误日志
        /// </summary>
        /// <param name="E">Exception类</param>
        public static void WriteLog(Exception E)
        {
            lock (Obj)
            {
                string Path = "";
                try
                {
                    Path = System.Configuration.ConfigurationManager.AppSettings["LogPath"].ToString();
                }
                catch (Exception e)
                {
                    Path = "/Log";
                }
                string p = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + Path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                Path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + Path;
                if (!Directory.Exists(Path))
                {
                    DirectoryInfo Dir = Directory.CreateDirectory(Path);
                    Dir.Refresh();
                }
                if (!File.Exists(p))
                {
                    FileStream fso = File.Create(p);
                    fso.Close();
                    fso.Dispose();

                    StreamWriter SW = File.AppendText(p);
                    SW.WriteLine("===================================================================================================");
                    SW.WriteLine("                           本站日志文件                          ");
                    SW.WriteLine("===================================================================================================");
                    SW.WriteLine("");
                    SW.Flush();
                    SW.Close();
                    SW.Dispose();
                }
                StreamWriter sw = File.AppendText(p);
                sw.WriteLine("");
                sw.WriteLine("===================================================================================================");
                sw.WriteLine("");
                sw.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]  ");
                sw.WriteLine("错误数据源:" + E.Source);
                sw.WriteLine("错误方法所属类:" + E.TargetSite.DeclaringType.Name.ToString());
                sw.WriteLine("错误方法:" + E.TargetSite.Name.ToString());
                try
                {
                    sw.WriteLine("当前IP:" + XiaoFeng.Function.GetIP4Address() + "");
                    sw.WriteLine("当前错误页面地址:" + System.Web.HttpContext.Current.Request.Url.ToString());
                }
                catch (Exception ex) { }
                sw.WriteLine("当前错误信息:" + E.Message.ToString());
                sw.Flush();
                sw.Close();
                sw.Dispose();
            }
        }
        #endregion
    }
}

 

-----------------------------------另一种简单的写日志的方法----------------------------------

 //记录LOG信息
        private void writelog(string info)
        {
            try
            {
                string Path = PathBase + "log" + DateTime.Now.ToLongDateString() + ".txt";//如果不存在则新建一个文件,存在的话就直接加进去
                System.IO.StreamWriter rw = new System.IO.StreamWriter(Path, true);
                rw.WriteLine(info + " --------- " + DateTime.Now.ToString());//加时间标签
                rw.Close();
            }
            catch
            {
                //
            }
        }

 

--------------------------------另一种简单的写日志的方法--------------------------------------

public static class ExpHelper
    {
        private static object logLock = new object();
        public static string fileConsolePath = Application.StartupPath + "\\txt\\cos_" + DateTime.Now.ToString().Replace(':', '.') + ".txt";
        public static string fileLogPath = Application.StartupPath + "\\txt\\log_" + DateTime.Now.ToString().Replace(':', '.') + ".txt";
        public static void Cos(string text)
        {
            File.AppendAllText(fileConsolePath, DateTime.Now.ToString() + "       " + text + Environment.NewLine);
        }

        public static void Log(string text)
        {
            lock(logLock)
            File.AppendAllText(fileLogPath, DateTime.Now.ToString() + "       " + text + Environment.NewLine);
        }
    }

------------------------------------------------------------------

    public static class WriteLogClass
    {
        /// <summary>
        /// 对象
        /// </summary>
        private static object logLock = new object();
        /// <summary>
        /// 应用程序的启动路径
        /// </summary>
        private static string PathBase = System.AppDomain.CurrentDomain.BaseDirectory;

        /// <summary>
        ///  写日志信息
        /// </summary>
        /// <param name="logInfo"></param>
        public static void WriteLog(string logInfo)
        {
            lock (logLock)
            {
                string Path = PathBase + "Log\\Log_" + DateTime.Now.ToLongDateString() + ".txt";

 

//string Path_add = Application.StartupPath + "\\Log\\log_" + DateTime.Now.ToLongDateString() + ".txt";
                //File.AppendAllText(Path_add, DateTime.Now.ToString() + "       " + logInfo + Environment.NewLine);
                System.IO.StreamWriter SW = new System.IO.StreamWriter(Path, true);//如果不存在则新建一个文件,存在的话就直接加进去
                try
                {
                    SW.WriteLine(DateTime.Now.ToString() + " --------- " + logInfo);//加时间标签
                }
                catch
                { }
                SW.Flush();
                SW.Close();
                SW.Dispose();
            }
        }
    }

posted @ 2013-11-07 12:22  Net-Spider  阅读(357)  评论(0)    收藏  举报