码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-08-25 09:54:14      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:os   io   文件   ar   art   cti   代码   log   new   

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


    }
}

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

标签:os   io   文件   ar   art   cti   代码   log   new   

原文地址:http://www.cnblogs.com/cxd4321/p/3934290.html

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