一种多线程写日志文件的解决方案 c#源代码演示

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using System.Timers;

namespace ComUtil
{
    public class LogWriter
    {
        private LogWriter()
        {
            logtimer.Stop();
            logtimer.Elapsed += new ElapsedEventHandler(logtimer_Elapsed);
        }

         private  void logtimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            string rootpath = System.AppDomain.CurrentDomain.BaseDirectory;

            if (!Directory.Exists(rootpath + "\\logs"))
            {
                Directory.CreateDirectory(rootpath + "\\logs");
            }


           
            while(LogList.Count>0)
            {
                StreamWriter Writer = new StreamWriter(rootpath + "\\logs\\" + LogList[0]["logfilename"].ToString(), true);
                StringBuilder wb = new StringBuilder();

                wb.Append("[");
                wb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                wb.Append("]");
                wb.Append("[");
                wb.Append(LogList[0]["logtype"].ToString());
                wb.Append("]");
                wb.Append(LogList[0]["msg"].ToString());
                wb.Append("\r\n");
                Writer.Write(wb.ToString());
                wb = wb.Remove(0, wb.Length);
                Writer.Flush();
                Writer.Close();

                LogList.RemoveAt(0);
            }

            logtimer.Stop();  //关闭定时器

        }

        private List<Hashtable> LogList = new List<Hashtable>();
        private static LogWriter mInstance = null;

        private Timer logtimer = new Timer(1000);

        public static LogWriter GetInstance()
        {
            if (mInstance==null)
            {
                mInstance = new LogWriter();
            }
            return mInstance;
        }

      
        public void WriteMessage(string msg,string logtype,string logfilename)
        {

            Hashtable newlog = new Hashtable();
            newlog.Add("msg", msg);
            newlog.Add("logtype", logtype);
            newlog.Add("logfilename", logfilename);
            LogList.Add(newlog);
            logtimer.Start();
        }


    }
}

转载于:https://www.cnblogs.com/cxd4321/p/3934290.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值