C#写文本日志帮助类(支持多线程)

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

 

    }

}

转载于:https://my.oschina.net/guanxinsui/blog/968088

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值