Logging.cs 2.8 KB
using Hh.Mes.Common.log;
using Hh.Mes.POJO.Entity;
using Hh.Mes.Service.Logs;
using System.Collections.Generic;
using System.Threading;


namespace WebMvc.Common
{
    public class Logging
    {
        private static Logging _log;
        private  static readonly object LockHelper = new object();
        private readonly int SleepTime = 10000;
        private readonly int logCount = 1;

        private Logging()
        {
        }

        public static Logging GetInstance
        {
            get
            {
                if (_log == null)
                {
                    lock (LockHelper)
                    {
                        if (_log == null)
                        {
                            _log = new Logging();
                        }
                    }
                }
                return _log;
            }
        }

        /// <summary>
        /// 写数据接口日志 只调用一次
        /// </summary>
        public void InitWriteInterLog()
        { 
            //接口
            ThreadPool.QueueUserWorkItem(o =>
            {
                var logs = new List<sys_interface_log>();
                while (true)
                {
                    if (QueueInterLog.GetInstance.Queue().Count>= logCount)
                    {
                        for (var i = 0; i < logCount; i++)
                        {
                            if (QueueInterLog.GetInstance.Queue().TryDequeue(out var log))
                            {
                                logs.Add(log);
                            }
                        }
                        new LogService().InsSysInterLog(logs);
                        logs.Clear();
                    }
                    else
                    {
                        Thread.Sleep(SleepTime);
                    }
                }
            });

            //定时器
            ThreadPool.QueueUserWorkItem(o =>
            {
                var jobLogs = new List<sys_job_log>();
                while (true)
                {
                    if (QueueJobLog.GetInstance.Queue().Count >= logCount)
                    {
                        for (var i = 0; i < logCount; i++)
                        {
                            if (QueueJobLog.GetInstance.Queue().TryDequeue(out var log))
                            {
                                jobLogs.Add(log);
                            }
                        }
                        new LogService().InsSysJobLog(jobLogs);
                        jobLogs.Clear();
                    }
                    else
                    {
                        Thread.Sleep(SleepTime);
                    }
                }
            });
            Log4NetHelper.Instance.Info("Interface log service  started successfully!");
        }
    }
}