zhaolei
8 days ago 921de2254ff5712a44ed8575ee8efe34252f6603
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
 
namespace Prow.Logging
{
    /// <summary>
    /// 日志文件内部操作类
    /// </summary>
    internal class FileLoggerWriter : IDisposable
    {
        private readonly BlockingCollection<LogMessage> _messageQueue = new BlockingCollection<LogMessage>(new ConcurrentQueue<LogMessage>());
        private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
        private readonly List<LogMessage> _currentBatch = new List<LogMessage>();
        private string? _logFolder;
        private string? _logFileName;
        private readonly Task _logTask;
 
        /// <summary>
        /// 获得/设置 日志配置项 FileLoggerOptions 实例
        /// </summary>
        public FileLoggerOptions Option { get; set; }
 
        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="option">日志配置项 FileLoggerOptions 实例</param>
        public FileLoggerWriter(FileLoggerOptions option)
        {
            Option = option;
            _logTask = Task.Run(ProcessLogQueue);
        }
 
        /// <summary>
        /// 写消息操作
        /// </summary>
        /// <param name="message">日志消息内容</param>
        public void WriteMessage(string message)
        {
            var msg = new LogMessage { Message = message, Timestamp = DateTimeOffset.Now };
#if NET45
            _logFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetDirectoryName(Option.FileName));
#else
            _logFolder = Path.Combine(AppContext.BaseDirectory, Path.GetDirectoryName(Option.FileName) ?? string.Empty);
#endif
            if (!Directory.Exists(_logFolder)) Directory.CreateDirectory(_logFolder);
            RollFilesAsync();
 
            if (Option.Batch && !_messageQueue.IsAddingCompleted) _messageQueue.Add(msg, _cancellationTokenSource.Token);
            else
            {
                _logFileName = $"{Path.GetFileNameWithoutExtension(Option.FileName)}-{msg.Timestamp:yyyyMMdd}{Path.GetExtension(Option.FileName)}";
                var fullName = Path.Combine(_logFolder, _logFileName);
                WriteToFile(fullName, msg.Message);
            }
        }
 
        private async Task ProcessLogQueue()
        {
            var cancelSource = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, _flushCancellationTokenSource.Token);
            while (!_cancellationTokenSource.IsCancellationRequested)
            {
                var limit = Option.BatchCount;
                while ((force || limit > 0) && _messageQueue.TryTake(out var message))
                {
                    _currentBatch.Add(message);
                    limit--;
                }
 
                if (_flushCancellationTokenSource.IsCancellationRequested)
                {
                    // force flush output
                    _flushCancellationTokenSource.Dispose();
                    _flushCancellationTokenSource = new CancellationTokenSource();
 
                    // 恢复强制输出开关
                    force = false;
                    cancelSource.Dispose();
                    cancelSource = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, _flushCancellationTokenSource.Token);
                }
 
                try
                {
                    if (_currentBatch.Any())
                    {
                        WriteMessagesToFile(_currentBatch);
                        _currentBatch.Clear();
                    }
                    await Task.Delay(Math.Max(1000, Option.Interval), cancelSource.Token);
                }
                catch (TaskCanceledException)
                {
                    if (_flushCancellationTokenSource.IsCancellationRequested)
                    {
                        force = true;
                        continue;
                    }
                    break;
                }
            }
            cancelSource.Dispose();
 
            // flush message to file
            while (_messageQueue.TryTake(out var message)) _currentBatch.Add(message);
            WriteMessagesToFile(_currentBatch);
        }
 
        private void WriteMessagesToFile(IEnumerable<LogMessage> messages)
        {
            foreach (var group in messages.GroupBy(m => new { m.Timestamp.Year, m.Timestamp.Month, m.Timestamp.Day }))
            {
                _logFileName = $"{Path.GetFileNameWithoutExtension(Option.FileName)}-{group.Key.Year:0000}{group.Key.Month:00}{group.Key.Day:00}{Path.GetExtension(Option.FileName)}";
                if (!string.IsNullOrEmpty(_logFolder))
                {
                    var fullName = Path.Combine(_logFolder, _logFileName);
                    WriteToFile(fullName, string.Join(string.Empty, group.Select(log => log.Message)));
                }
            }
        }
 
        private readonly object _writeLocker = new object();
        private void WriteToFile(string fileName, string content)
        {
            lock (_writeLocker)
            {
                using var streamWriter = File.AppendText(fileName);
                streamWriter.WriteLine(content);
            }
        }
 
        private void RollFilesAsync()
        {
            if (Option.MaxFileCount > 0)
            {
                Task.Run(() =>
                {
                    var rollFile = Directory
                    .EnumerateFiles(_logFolder, $"{Path.GetFileNameWithoutExtension(Option.FileName)}*{Path.GetExtension(Option.FileName)}")
                    .FirstOrDefault(f =>
                    {
                        var fn = Path.GetFileNameWithoutExtension(f);
#if !NET45
                        return fn.Length > 8 && fn.AsSpan().Slice(fn.Length - 8).ToString().CompareTo(DateTimeOffset.Now.AddDays(0 - Option.MaxFileCount).ToString("yyyyMMdd")) < 1;
#else
                        return fn.Length > 8 && fn.Substring(fn.Length - 8).CompareTo(DateTimeOffset.Now.AddDays(0 - Option.MaxFileCount).ToString("yyyyMMdd")) < 1;
#endif
                    });
                    if (!string.IsNullOrEmpty(rollFile)) File.Delete(rollFile);
                });
            }
        }
 
        private bool force;
        private CancellationTokenSource _flushCancellationTokenSource = new CancellationTokenSource();
        /// <summary>
        /// 强制输出到日志文件中
        /// </summary>
        public void Flush() => _flushCancellationTokenSource.Cancel();
 
        /// <summary>
        /// Dispose 方法
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
 
        private bool disposedValue; // To detect redundant calls
 
        /// <summary>
        /// Dispose 重载方法
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                disposedValue = true;
                if (disposing)
                {
                    _messageQueue.CompleteAdding();
                    _cancellationTokenSource.Cancel();
                    _logTask.Wait(Option.TaskWaitTime);
 
                    _cancellationTokenSource.Dispose();
                    _messageQueue.Dispose();
                }
            }
        }
 
        private struct LogMessage
        {
            /// <summary>
            /// 时间戳
            /// </summary>
            public DateTimeOffset Timestamp { get; set; }
 
            /// <summary>
            /// 消息体
            /// </summary>
            public string Message { get; set; }
        }
    }
}