• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

代码:

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

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

        #region 构造函数
        static LogUtil()
        {
            Task.Factory.StartNew(new Action(delegate()
            {
                StringBuilder log;
                string path;
                Tuple<string, DateTime> tuple;
                string 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 - 2), path);
                    Thread.Sleep(100);
                }
            }));
        }
        #endregion

        #region 写文件
        /// <summary>
        /// 写文件
        /// </summary>
        public static void WriteFile(string log, string path)
        {
            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(path)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                }

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

                using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.WriteLine(log);
                        sw.Flush();
                    }
                    fs.Close();
                }
            }
            catch { }
        }
        #endregion

        #region 生成日志文件路径
        /// <summary>
        /// 生成日志文件路径
        /// </summary>
        public static string CreateLogPath()
        {
            int index = 0;
            string logPath;
            bool bl = true;
            do
            {
                index++;
                logPath = Path.Combine(path, "Log" + DateTime.Now.ToString("yyyyMMdd") + (index == 1 ? "" : "_" + index.ToString()) + ".txt");
                if (File.Exists(logPath))
                {
                    FileInfo fileInfo = new FileInfo(logPath);
                    if (fileInfo.Length < fileSize)
                    {
                        bl = false;
                    }
                }
                else
                {
                    bl = false;
                }
            } while (bl);

            return logPath;
        }
        #endregion

        #region 写错误日志
        /// <summary>
        /// 写错误日志
        /// </summary>
        public static void LogError(string log)
        {
            queue.Enqueue(new Tuple<string, DateTime>("[Error] " + log, DateTime.Now));
        }
        #endregion

        #region 写操作日志
        /// <summary>
        /// 写操作日志
        /// </summary>
        public static void Log(string log)
        {
            queue.Enqueue(new Tuple<string, DateTime>("[Info]  " + log, DateTime.Now));
        }
        #endregion

    }
}
View Code

测试代码:

private 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(object 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

效果图:

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
ASP.NETCoreSignalR(十一):托管和扩展-钱行慕发布时间:2022-07-10
下一篇:
Asp.net Json数据解析的一种思路发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap