分享

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

 kittywei 2015-06-17

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();
        }



    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多