微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#写文本日志帮助类(支持多线程)改进版(不适用于ASP.NET程序)

由于iis的自动回收机制,不适用于ASP.NET程序

代码

using System;
 System.Collections.Concurrent;
 System.Configuration;
 System.IO;
 System.Text;
 System.Threading;
 System.Threading.Tasks;

namespace CommonDll
{
    /// <summary>
    /// 写日志类
    </summary>
    public class LogUtil
    {
        #region 字段
        static string path = ConfigurationManager.AppSettings["LogPath"];
        int fileSize = 10 * 1024 * 1024; //日志分隔文件大小
        private static ConcurrentQueue<Tuple<string,DateTime>> queue = new ConcurrentQueue<Tuple<();
        #endregion

        #region 构造函数
        static LogUtil()
        {
            Task.Factory.StartNew(new Action(delegate()
            {
                StringBuilder log;
                string path;
                Tuple< tuple;
                 item;

                while (true)
                {
                    log = new StringBuilder();
                    path = CreateLogPath();

                    while (queue.TryDequeue(out tuple))
                    {
                        item = string.Format(@"{0} {1}",tuple.Item2.ToString(yyyy-MM-dd HH:mm:ss.fff),tuple.Item1);
                        log.AppendFormat(\r\n{0},item);
                    }

                    if (log.Length > 0) WriteFile(log.ToString(2,log.Length - 2100);
                }
            }));
        }
        #region文件
        <summary>
        文件
        </summary>
        void WriteFile(string log, path)
        {
            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(path)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                }

                File.Exists(path))
                {
                    using (FileStream fs =  FileStream(path,FileMode.Create)) { fs.Close(); }
                }

                using (StreamWriter sw =  StreamWriter(fs))
                    {
                        sw.WriteLine(log);
                        sw.Flush();
                    }
                    fs.Close();
                }
            }
            catch { }
        }
        #region 生成日志文件路径
         生成日志文件路径
         CreateLogPath()
        {
            int index = 0;
             logPath;
            bool bl = do
            {
                index++;
                logPath = Path.Combine(path,Log" + DateTime.Now.ToString(yyyyMMdd") + (index == 1 ? "" : _" + index.ToString()) + .txt);
                if (File.Exists(logPath))
                {
                    FileInfo fileInfo =  FileInfo(logPath);
                    if (fileInfo.Length < fileSize)
                    {
                        bl = false;
                    }
                }
                else
                {
                    bl = ;
                }
            } while (bl);

            return logPath;
        }
        #region错误日志
        错误日志
        void LogError( log)
        {
            queue.Enqueue(new Tuple<[Error] " + log,DateTime.Now));
        }
        #region 写操作日志
         写操作日志
        void Log([Info]  #endregion

    }
}
View Code

测试代码

void button1_Click(object sender,EventArgs e)
{
    int n = 10000;
    DateTime dtStart = DateTime.Now;
    for (int i = 1; i <= n; i++)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(delegate( obj)
        {
            int j = (int)obj;
            LogUtil.Log(测试" + j.ToString(00000));

            if (j == n)
            {
                double sec = DateTime.Now.Subtract(dtStart).TotalSeconds;
                MessageBox.Show(n + 条日志完成,耗时" + sec.ToString(0.000") + );
            }
        }),i);
    }
}
View Code

效果图:

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐