C#写文本日志帮助类_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > C#写文本日志帮助类

C#写文本日志帮助类

 2014/10/14 12:45:05  秋荷雨翔  程序员俱乐部  我要评论(0)
  • 摘要:代码:usingSystem;usingSystem.Configuration;usingSystem.IO;usingSystem.Threading;namespaceFQDService.Utils{///<summary>///写日志类///</summary>publicclassFileLogger{#region字段publicstaticreadonlyobject_lock=newobject();#endregion#region写文件///<
  • 标签:C#

代码:

class="code_img_closed" src="/Upload/Images/2014101412/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('11d4d22c-c12b-44e2-b5f5-c8d5fcf0ab57',event)" src="/Upload/Images/2014101412/2B1B950FA3DF188F.gif" alt="" />
using System;
using System.Configuration;
using System.IO;
using System.Threading;

namespace FQDService.Utils
{
    /// <summary>
    /// 写日志类
    /// </summary>
    public class FileLogger
    {
        #region 字段
        public static readonly object _lock = new object();
        #endregion

        #region 写文件
        /// <summary>
        /// 写文件
        /// </summary>
        public static void WriteFile(string log, string path)
        {
            Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)
            {
                lock (_lock)
                {
                    if (!File.Exists(path))
                    {
                        using (FileStream fs = new FileStream(path, FileMode.Create)) { }
                    }

                    using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            #region 日志内容
                            string value = string.Format(@"{0}
--------------------------------------------------------
{1}

", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), obj.ToString());
                            #endregion

                            sw.WriteLine(value);
                            sw.Flush();
                        }
                    }
                }
            }));
            thread.Start(log);
        }
        #endregion

        #region 写日志
        /// <summary>
        /// 写日志
        /// </summary>
        public static void WriteLog(string log)
        {
            string logPath = ConfigurationManager.AppSettings["LogPath"] + "\\FQDService_Log.txt";
            WriteFile(log, logPath);
        }
        #endregion

        #region错误日志
        /// <summary>
        /// 写错误日志
        /// </summary>
        public static void WriteErrorLog(string log)
        {
            string logPath = ConfigurationManager.AppSettings["LogPath"] + "\\FQDService_ErrorLog.txt";
            WriteFile(log, logPath);
        }
        #endregion

    }
}
View Code

 

发表评论
用户名: 匿名