一个关于日志操作方法

 public static class LogHelper<T>
    {
        private static System.Timers.Timer _timer;
        private static ConcurrentDictionary<string, ConcurrentQueue<T>> _dic = new ConcurrentDictionary<string, ConcurrentQueue<T>>();

        static LogHelper()
        {
            _dic = new ConcurrentDictionary<string, ConcurrentQueue<T>>();
            _timer = new System.Timers.Timer();
            _timer.Interval = 1000*60;
            _timer.Enabled = true;
            _timer.Start();
            _timer.Elapsed += _timer_Elapsed;
        }

        private static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            foreach (var key in _dic.Keys)
            {
                ConcurrentQueue<T> q;
                var has = _dic.TryGetValue(key, out q);
                if (!has)
                    continue;

                List<T> lst = new List<T>();
                while (q.Count > 0)
                {
                    T obj;
                    var hasorder = q.TryDequeue(out obj);
                    if (hasorder)
                        lst.Add(obj);
                }
                if (lst.Count > 0)
                {
                    var str = Newtonsoft.Json.JsonConvert.SerializeObject(lst);

                    string pushDataSavePatch = ConfigurationManager.AppSettings["PushDataPath"];

                    var fileName = DateTime.Today.ToString("yyyy-MM-dd");
                    var fileRoad = pushDataSavePatch + "\\" + fileName;
                    if (Directory.Exists(fileRoad) == false)//如果不存在就创建file文件夹
                    {
                        Directory.CreateDirectory(fileRoad);
                    }

                    string filePath = fileRoad + $"\\{key}.txt";
                    if (File.Exists(filePath))
                    {
                        using (StreamWriter sw = File.AppendText(filePath))
                        {
                            sw.WriteLine(str);
                        }
                    }
                    else
                    {
                        File.WriteAllText(filePath, str + "\r\n");
                    }



                }

            }
        }

        public static void Log(string key, T obj)
        {
            _dic.TryAdd(key, new ConcurrentQueue<T>());
            ConcurrentQueue<T> q;
            _dic.TryGetValue(key, out q);
            q.Enqueue(obj);
        }

    }

调用

                    LogHelper<string>.Log("TestLog", jsonStr);

 

posted @ 2017-06-01 11:22  码农丁  阅读(189)  评论(0编辑  收藏  举报