C3204
2026-01-04 2337f47091dbcc1a681f63fc18d9b8d28ab22296
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
using log4net;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace LB_SmartVisionCommon
{
    /// <summary>
    /// 异步记录日志类
    /// </summary>
    public static class AsyncLogHelper
    {
        private static readonly BlockingCollection<LogItem> _logQueue = new BlockingCollection<LogItem>(2000);
        private static readonly Task _backgroundTask;
        private static readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
 
        static string LineT = "记录信息:";
        static readonly ILog _logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
 
        static AsyncLogHelper()
        {
            // 启动后台日志处理任务
            _backgroundTask = Task.Factory.StartNew(
                ProcessLogQueue,
                _cancellationTokenSource.Token,
                TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
 
            // 注册应用程序退出时的清理
            AppDomain.CurrentDomain.ProcessExit += (s, e) => Dispose();
            AppDomain.CurrentDomain.DomainUnload += (s, e) => Dispose();
        }
 
        /// <summary>
        /// Info类型 - 异步记录
        /// </summary>
        public static void Info(string message)
        {
            EnqueueLog(LogLevel.Info, message);
        }
 
        /// <summary>
        /// Debug类型 - 异步记录
        /// </summary>
        public static void Debug(string message)
        {
            EnqueueLog(LogLevel.Debug, message);
        }
 
        /// <summary>
        /// Warn类型 - 异步记录
        /// </summary>
        public static void Warn(string message)
        {
            EnqueueLog(LogLevel.Warn, message);
        }
 
        /// <summary>
        /// Error类型 - 异步记录
        /// </summary>
        public static void Error(string message)
        {
            EnqueueLog(LogLevel.Error, message);
        }
 
        /// <summary>
        /// Error类型 - 异步记录异常
        /// </summary>
        public static void Error(string message, Exception exception)
        {
            EnqueueLog(LogLevel.Error, message, exception);
        }
 
        private static void EnqueueLog(LogLevel level, string message, Exception exception = null)
        {
            if (!_logQueue.IsAddingCompleted)
            {
                var logItem = new LogItem
                {
                    Level = level,
                    Message = LineT + message,
                    Exception = exception,
                    Timestamp = DateTime.Now
                };
 
                // 如果队列已满,等待一段时间
                if (!_logQueue.TryAdd(logItem, 100))
                {
                    // 队列满时的降级处理:同步记录或丢弃
                    try
                    {
                        WriteLogSync(logItem);
                    }
                    catch
                    {
                        // 忽略同步记录时的异常
                    }
                }
            }
        }
 
        private static void ProcessLogQueue()
        {
            foreach (var logItem in _logQueue.GetConsumingEnumerable(_cancellationTokenSource.Token))
            {
                try
                {
                    WriteLogSync(logItem);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"异步日志记录失败: {ex.Message}");
                }
            }
        }
 
        private static void WriteLogSync(LogItem logItem)
        {
            switch (logItem.Level)
            {
                case LogLevel.Debug:
                    _logger.Debug(logItem.Message, logItem.Exception);
                    break;
                case LogLevel.Info:
                    _logger.Info(logItem.Message, logItem.Exception);
                    break;
                case LogLevel.Warn:
                    _logger.Warn(logItem.Message, logItem.Exception);
                    break;
                case LogLevel.Error:
                    _logger.Error(logItem.Message, logItem.Exception);
                    break;
            }
        }
 
        /// <summary>
        /// 释放资源,确保所有日志都被处理
        /// </summary>
        public static void Dispose()
        {
            try
            {
                _logQueue.CompleteAdding();
                _cancellationTokenSource.CancelAfter(5000); // 5秒后强制取消
 
                // 等待任务完成,最多等待10秒
                if (!_backgroundTask.Wait(10000))
                {
                    System.Diagnostics.Debug.WriteLine("日志任务未在超时时间内完成");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"释放日志资源时出错: {ex.Message}");
            }
        }
    }
 
    internal enum LogLevel
    {
        Debug,
        Info,
        Warn,
        Error
    }
 
    internal class LogItem
    {
        public LogLevel Level { get; set; }
        public string Message { get; set; }
        public Exception Exception { get; set; }
        public DateTime Timestamp { get; set; }
    }
}