C3032
2025-12-20 15492363f898704b51afce5f1c88fa3b754cbabc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace SmartScanner.OperateLog
{
    public static class OperateLogService
    {
        private static readonly string logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
        private static readonly string logFileName = $"OperationLog_{DateTime.Now:yyyyMMdd}.txt";
 
        static OperateLogService()
        {
            // 确保日志目录存在
            if (!Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
            }
        }
 
        public static void LogOperation(string operationType, string operationDetails, string targetDevice = null)
        {
            if (UserManager.CurrentUser == null) return;
 
            try
            {
                var logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} | " +
                              $"操作人员: {UserManager.CurrentUser.Username} | " +
                              $"操作类型: {operationType} | " +
                              $"目标设备: {targetDevice ?? "N/A"} | " +
                              $"操作详情: {operationDetails}";
 
                var logPath = Path.Combine(logDirectory, logFileName);
                File.AppendAllText(logPath, logEntry + Environment.NewLine);
            }
            catch (Exception ex)
            {
                // 简单处理日志写入错误
                Console.WriteLine($"日志记录失败: {ex.Message}");
            }
        }
 
        public static string[] GetRecentLogs(int days = 7)
        {
            try
            {
                var logFiles = Directory.GetFiles(logDirectory, "OperationLog_*.txt")
                                      .OrderByDescending(f => f)
                                      .Take(days)
                                      .ToList();
 
                var allLogs = new List<string>();
                foreach (var file in logFiles)
                {
                    allLogs.AddRange(File.ReadAllLines(file));
                }
 
                return allLogs.ToArray();
            }
            catch
            {
                return new string[0];
            }
        }
    }
}