ソースを参照

状态记录优化,并增加活动窗口记录

yuzhengyang 5 年 前
コミット
cd8029823e

+ 2 - 0
Azylee.Utils/Azylee.Core/Azylee.Core.csproj

@@ -119,6 +119,8 @@
     <Compile Include="IOUtils\TxtUtils\IniTool.cs" />
     <Compile Include="IOUtils\TxtUtils\IniTool.cs" />
     <Compile Include="IOUtils\TxtUtils\TxtTool.cs" />
     <Compile Include="IOUtils\TxtUtils\TxtTool.cs" />
     <Compile Include="IOUtils\TxtUtils\XmlTool.cs" />
     <Compile Include="IOUtils\TxtUtils\XmlTool.cs" />
+    <Compile Include="LogUtils\FormActiveLogUtils\FormActiveLog.cs" />
+    <Compile Include="LogUtils\FormActiveLogUtils\FormActiveLogModel.cs" />
     <Compile Include="LogUtils\SimpleLogUtils\Log.cs" />
     <Compile Include="LogUtils\SimpleLogUtils\Log.cs" />
     <Compile Include="LogUtils\SimpleLogUtils\LogLevel.cs" />
     <Compile Include="LogUtils\SimpleLogUtils\LogLevel.cs" />
     <Compile Include="LogUtils\SimpleLogUtils\LogModel.cs" />
     <Compile Include="LogUtils\SimpleLogUtils\LogModel.cs" />

+ 162 - 0
Azylee.Utils/Azylee.Core/LogUtils/FormActiveLogUtils/FormActiveLog.cs

@@ -0,0 +1,162 @@
+using Azylee.Core.DataUtils.CollectionUtils;
+using Azylee.Core.DataUtils.StringUtils;
+using Azylee.Core.IOUtils.DirUtils;
+using Azylee.Core.IOUtils.FileUtils;
+using Azylee.Core.IOUtils.TxtUtils;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+
+namespace Azylee.Core.LogUtils.FormActiveLogUtils
+{
+    public sealed class FormActiveLog
+    {
+        #region 单例模式
+        private static FormActiveLog _inst;
+        private static readonly object syncObject = new object();
+        private FormActiveLog() { }
+        public static FormActiveLog Instance
+        {
+            get
+            {
+                if (_inst == null)
+                    lock (syncObject)
+                        if (_inst == null)
+                            _inst = new FormActiveLog();
+                return _inst;
+            }
+        }
+        #endregion
+
+        #region 基础属性
+        const string LOG_PATH = @"azylee.log";//存储路径
+        const int Interval = 1000;//监测间隔时间
+
+        private int CACHE_DAYS = 30;//缓存天数
+        private string LogPath = AppDomain.CurrentDomain.BaseDirectory + LOG_PATH;//存储路径
+        private DateTime Time = DateTime.Now;//标记当前时间
+        private Task Listener = null;//监测任务
+        private Process AppProcess = Process.GetCurrentProcess();
+        private CancellationTokenSource CancelToken = new CancellationTokenSource();//监测取消Token
+        #endregion
+
+        public void SetLogPath(string path)
+        {
+            if (!string.IsNullOrWhiteSpace(path))
+            {
+                LogPath = DirTool.Combine(path, LOG_PATH);
+            }
+        }
+        public void SetCacheDays(int days)
+        {
+            if (days >= 0) CACHE_DAYS = days;
+        }
+
+        public bool Start()
+        {
+            //如果任务停止运行,则重新创建Token,并释放上次任务
+            if (Listener != null && Listener.Status != TaskStatus.Running)
+            {
+                try
+                {
+                    CancelToken = new CancellationTokenSource();
+                    Listener.Dispose();
+                }
+                catch { }
+            }
+            //如果任务没取消,并且没有运行任务,则运行任务
+            if (!CancelToken.IsCancellationRequested && (Listener == null || Listener.Status != TaskStatus.Running))
+            {
+                Listener = Task.Factory.StartNew(() =>
+                {
+                    try
+                    {
+                        FormActiveLogModel active = new FormActiveLogModel();
+                        while (!CancelToken.IsCancellationRequested)
+                        {
+                            active.EndTime = DateTime.Now;
+
+                            Form form = Form.ActiveForm;
+                            if ((form?.Name ?? "") != active.FormName)
+                            {
+                                WriteStatus(active);//写出数据
+                                active.FormName = form?.Name ?? "";
+                                active.FormText = form?.Text ?? "";
+                                active.BeginTime = DateTime.Now;
+                            }
+
+                            Thread.Sleep(Interval);//等待间隔时间
+                        }
+                    }
+                    catch { }
+                }, CancelToken.Token);
+                return true;
+            }
+            return false;
+        }
+        public bool Stop()
+        {
+            try
+            {
+                if (!CancelToken.IsCancellationRequested)
+                {
+                    CancelToken.Cancel();
+                }
+                return true;
+            }
+            catch { return false; }
+        }
+        /// <summary>
+        /// 写出运行时状态信息
+        /// </summary>
+        private void WriteStatus(FormActiveLogModel status)
+        {
+            try
+            {
+                if (status != null)// && Str.Ok(status.FormName, status.FormText))// && status.Duration > 0
+                {
+                    //设置日志目录和日志文件
+                    string path = DirTool.Combine(LogPath, "form_active");
+                    string file = DirTool.Combine(path, DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
+                    //创建日志目录
+                    DirTool.Create(path);
+                    //写出日志
+                    TxtTool.Append(file, status.ToString());
+                }
+                Cleaner();
+            }
+            catch { }
+        }
+        /// <summary>
+        /// 清理过多的状态信息文件
+        /// </summary>
+        private void Cleaner()
+        {
+            string path = DirTool.Combine(LogPath, "form_active");
+            List<string> files = FileTool.GetFile(path);
+            if (ListTool.HasElements(files))
+            {
+                files.ForEach(f =>
+                {
+                    try
+                    {
+                        string filename = Path.GetFileNameWithoutExtension(f);
+                        if (filename.Length == 10)
+                        {
+                            DateTime date = DateTime.Parse(filename);
+                            if (date < Time.AddDays(-CACHE_DAYS - 1)) FileTool.Delete(f);
+                        }
+                        else { FileTool.Delete(f); }
+                    }
+                    catch { FileTool.Delete(f); }
+                });
+            }
+        }
+    }
+}

+ 29 - 0
Azylee.Utils/Azylee.Core/LogUtils/FormActiveLogUtils/FormActiveLogModel.cs

@@ -0,0 +1,29 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace Azylee.Core.LogUtils.FormActiveLogUtils
+{
+    public class FormActiveLogModel
+    {
+        public DateTime BeginTime { get; set; }
+        public DateTime EndTime { get; set; }
+        public long Duration { get { return (long)(EndTime - BeginTime).TotalSeconds; } }
+        public string FormName { get; set; }
+        public string FormText { get; set; }
+
+        public FormActiveLogModel()
+        {
+            BeginTime = DateTime.Now;
+            EndTime = DateTime.Now;
+            FormName = "";
+            FormText = "";
+        }
+        public override string ToString()
+        {
+            string s = $"{BeginTime}|{EndTime}|{Duration}|{FormName}|{FormText}";
+            return s;
+        }
+    }
+}

+ 18 - 14
Azylee.Utils/Azylee.Core/LogUtils/StatusLogUtils/StatusLog.cs

@@ -44,7 +44,6 @@ namespace Azylee.Core.LogUtils.StatusLogUtils
         #region 基础属性
         #region 基础属性
         const string LOG_PATH = @"azylee.log";//存储路径
         const string LOG_PATH = @"azylee.log";//存储路径
         const int Interval = 1000;//监测间隔时间
         const int Interval = 1000;//监测间隔时间
-        const int WriteInterval = 60 * Interval;//写出间隔时间
 
 
         private int CACHE_DAYS = 30;//缓存天数
         private int CACHE_DAYS = 30;//缓存天数
         private string LogPath = AppDomain.CurrentDomain.BaseDirectory + LOG_PATH;//存储路径
         private string LogPath = AppDomain.CurrentDomain.BaseDirectory + LOG_PATH;//存储路径
@@ -84,30 +83,33 @@ namespace Azylee.Core.LogUtils.StatusLogUtils
             {
             {
                 Listener = Task.Factory.StartNew(() =>
                 Listener = Task.Factory.StartNew(() =>
                 {
                 {
+                    try { WriteConfig(); } catch { }
                     try
                     try
                     {
                     {
-                        WriteConfig();
-                        int runtime = 0;//运行时间(毫秒)
                         long afk = WindowsAPI.GetLastInputTime();//空闲时间缓存
                         long afk = WindowsAPI.GetLastInputTime();//空闲时间缓存
                         TimeSpan pin = TimeSpan.Zero;//程序运行时间戳
                         TimeSpan pin = TimeSpan.Zero;//程序运行时间戳
                         StatusLogModel status = null;//运行状态信息模型
                         StatusLogModel status = null;//运行状态信息模型
+                        DateTime recCycTime = DateTime.Now;
+                        int count = 1;
                         while (!CancelToken.IsCancellationRequested)
                         while (!CancelToken.IsCancellationRequested)
                         {
                         {
                             pin = AppProcess.TotalProcessorTime;//程序运行时间戳
                             pin = AppProcess.TotalProcessorTime;//程序运行时间戳
-                            runtime += Interval;//增加运行时间
                             Thread.Sleep(Interval);//等待间隔时间
                             Thread.Sleep(Interval);//等待间隔时间
 
 
                             //每秒钟都会执行的操作
                             //每秒钟都会执行的操作
-                            CollectStatus(ref status, runtime, afk, pin);//收集数据
-                            afk = WindowsAPI.GetLastInputTime();//空闲时间缓存
+                            DateTime now = DateTime.Now;
+                            int time = (int)(now - recCycTime).TotalMilliseconds;
+                            CollectStatus(ref status, count, time, ref afk, pin);//收集数据
 
 
-                            //每分钟进行汇总输出
-                            if (runtime >= WriteInterval)
+                            if (!(recCycTime.Year == now.Year && recCycTime.Month == now.Month && recCycTime.Day == now.Day && recCycTime.Hour == now.Hour && recCycTime.Minute == now.Minute))
                             {
                             {
-                                WriteStatus(status);//写出数据
-                                runtime = 0;//重置运行时间
+                                WriteStatus(status);//写出数据                    
+                                count = 1;//重置运行时间
                                 status = null;//重置数据
                                 status = null;//重置数据
+                                recCycTime = DateTime.Now;
                             }
                             }
+
+                            count++;
                         }
                         }
                     }
                     }
                     catch { }
                     catch { }
@@ -146,18 +148,19 @@ namespace Azylee.Core.LogUtils.StatusLogUtils
         /// 收集数据
         /// 收集数据
         /// </summary>
         /// </summary>
         /// <returns></returns>
         /// <returns></returns>
-        private bool CollectStatus(ref StatusLogModel status, int runtime, long afk, TimeSpan pin)
+        private bool CollectStatus(ref StatusLogModel status, int count, int runtime, ref long afk, TimeSpan pin)
         {
         {
             try
             try
             {
             {
-                int count = runtime / Interval;//收集次数,用来帮助平均值计算
-
                 if (status == null) status = new StatusLogModel() { Time = DateTime.Now };
                 if (status == null) status = new StatusLogModel() { Time = DateTime.Now };
                 //固定值数据
                 //固定值数据
                 status.Long = runtime;//运行时长
                 status.Long = runtime;//运行时长
                 //累计值数据
                 //累计值数据
-                long afktemp = WindowsAPI.GetLastInputTime() - afk;
+                long nowAfk = WindowsAPI.GetLastInputTime();
+                long afktemp = nowAfk - afk;
                 if (afktemp > 0) status.AFK = status.AFK + afktemp;
                 if (afktemp > 0) status.AFK = status.AFK + afktemp;
+                Console.WriteLine($"nowAfk: {nowAfk}, afk: {afk}, afktemp: {afktemp}, statusAFK: {status.AFK}");
+                afk = nowAfk;
                 //计算平均值数据
                 //计算平均值数据
                 int cpu = 0;
                 int cpu = 0;
                 try { cpu = (int)ComputerProcessor.NextValue(); } catch { }//CPU占用
                 try { cpu = (int)ComputerProcessor.NextValue(); } catch { }//CPU占用
@@ -187,6 +190,7 @@ namespace Azylee.Core.LogUtils.StatusLogUtils
                     //处理比率
                     //处理比率
                     status.Long = status.Long / 1000;
                     status.Long = status.Long / 1000;
                     status.AFK = status.AFK / 1000;
                     status.AFK = status.AFK / 1000;
+                    if (status.AFK > status.Long) status.AFK = status.Long;
 
 
                     //设置日志目录和日志文件
                     //设置日志目录和日志文件
                     string path = DirTool.Combine(LogPath, "status");
                     string path = DirTool.Combine(LogPath, "status");

+ 1 - 1
Azylee.Utils/Azylee.Core/LogUtils/StatusLogUtils/StatusLogModel.cs

@@ -57,7 +57,7 @@ namespace Azylee.Core.LogUtils.StatusLogUtils
                 $"{RamFree}|{SysDriveFree}|{AppCpuPer}|{AppRamUsed}";
                 $"{RamFree}|{SysDriveFree}|{AppCpuPer}|{AppRamUsed}";
             return s;
             return s;
         }
         }
-        public StatusLogModel FromString(string s)
+        public static StatusLogModel FromString(string s)
         {
         {
             StatusLogModel model = new StatusLogModel();
             StatusLogModel model = new StatusLogModel();
             string[] elements = s.Split('|');
             string[] elements = s.Split('|');

+ 6 - 1
Azylee.Utils/Tests/Test.Toast/Program.cs

@@ -1,4 +1,5 @@
-using System;
+using Azylee.Core.LogUtils.StatusLogUtils;
+using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
@@ -16,6 +17,10 @@ namespace Test.Toast
         {
         {
             Application.EnableVisualStyles();
             Application.EnableVisualStyles();
             Application.SetCompatibleTextRenderingDefault(false);
             Application.SetCompatibleTextRenderingDefault(false);
+
+            StatusLog.Instance.Start();//启动计算机状态日志记录
+            StatusLog.Instance.SetCacheDays(10);//保存最近10天的状态日志信息
+
             Application.Run(new Form1());
             Application.Run(new Form1());
         }
         }
     }
     }