码迷,mamicode.com
首页 > Windows程序 > 详细

C#写文本日志帮助类

时间:2014-10-14 12:28:58      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   文件   

代码:

bubuko.com,布布扣
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

 

C#写文本日志帮助类

标签:style   blog   http   color   io   os   ar   for   文件   

原文地址:http://www.cnblogs.com/s0611163/p/4023859.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!