zhaolei
7 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#if !NET45
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Runtime.InteropServices;
#endif
using System;
using System.Collections.Specialized;
using System.Text;
 
namespace Prow.Logging
{
    /// <summary>
    /// 
    /// </summary>
    internal class Logger : ILogger
    {
        /// <summary>
        /// 
        /// </summary>
        protected Action<string>? LogCallback { get; set; }
 
        /// <summary>
        /// 
        /// </summary>
        protected string Name { get; set; }
 
        /// <summary>
        /// 
        /// </summary>
        protected Func<string, LogLevel, bool> Filter { get; set; }
 
        private StringBuilder _logBuilder;
        private readonly bool _includeScope;
 
        /// <summary>
        /// 判断当前 logLevel 是否开启日志
        /// </summary>
        /// <param name="logLevel">LogLevel 实例</param>
        /// <returns>开启日志时返回真</returns>
        public virtual bool IsEnabled(LogLevel logLevel) => logLevel == LogLevel.None ? false : Filter(Name, logLevel);
 
#if !NET45
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="logCallback"></param>
        /// <param name="filter"></param>
        /// <param name="scopeProvider"></param>
        /// <param name="config"></param>
        public Logger(string name, Action<string>? logCallback, Func<string, LogLevel, bool>? filter, IExternalScopeProvider? scopeProvider, IConfiguration? config)
        {
            Configuration = config;
            ScopeProvider = scopeProvider;
            Name = name;
            LogCallback = logCallback;
            Filter = filter ?? ((category, logLevel) => true);
 
            _includeScope = ScopeProvider != null;
            _logBuilder = new StringBuilder();
        }
 
        /// <summary>
        /// 获得/设置 IConfiguration 实例
        /// </summary>
        public IConfiguration? Configuration { get; set; }
 
        /// <summary>
        /// 获得/设置 IExternalScopeProvider 实例
        /// </summary>
        public IExternalScopeProvider? ScopeProvider { get; set; }
 
        /// <summary>
        /// 开始创建日志上下文作用域
        /// </summary>
        /// <typeparam name="TState"></typeparam>
        /// <param name="state"></param>
        /// <returns></returns>
        public IDisposable BeginScope<TState>(TState state) => ScopeProvider?.Push(state) ?? NullScope.Instance;
 
        /// <summary>
        /// 写日志方法
        /// </summary>
        /// <typeparam name="TState">泛型类型</typeparam>
        /// <param name="logLevel">LogLevel 实例</param>
        /// <param name="eventId">eventId 实例</param>
        /// <param name="state">TState 实例</param>
        /// <param name="exception">Exception 实例</param>
        /// <param name="formatter">格式化方法回调函数</param>
        public virtual void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel)) return;
 
            var message = formatter?.Invoke(state, exception);
            if (!string.IsNullOrEmpty(message) || exception != null)
            {
                WriteMessage(logLevel, Name, eventId.Id, message, exception, state);
            }
        }
 
        private void GetScopeInformation(StringBuilder stringBuilder, string messagePadding)
        {
            if (ScopeProvider != null)
            {
                var initialLength = stringBuilder.Length;
 
                ScopeProvider.ForEachScope((scope, state) =>
                {
                    var (builder, length) = state;
                    var first = length == builder.Length;
                    builder.Append(first ? "=> " : " => ").Append(scope);
                }, (stringBuilder, initialLength));
 
                if (stringBuilder.Length > initialLength)
                {
                    stringBuilder.Insert(initialLength, messagePadding);
                    stringBuilder.AppendLine();
                }
            }
        }
#else
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="logCallback"></param>
        /// <param name="filter"></param>
        /// <param name="includeScope"></param>
        public Logger(string name, Action<string>? logCallback, Func<string, LogLevel, bool>? filter, bool? includeScope)
        {
            _includeScope = includeScope ?? true;
            _logBuilder = new StringBuilder();
            Name = name;
            LogCallback = logCallback;
            Filter = filter ?? ((category, logLevel) => true);
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="logLevel"></param>
        /// <param name="message"></param>
        public virtual void Log(LogLevel logLevel, string message)
        {
            if (!IsEnabled(logLevel)) return;
            LogCallback?.Invoke(message);
        }
#endif
 
        protected virtual void WriteMessage<TState>(LogLevel logLevel, string logName, int eventId, string? message, Exception exception, TState state)
        {
            var messagePadding = string.Empty;
            // 根据配置是否输出 Scope 信息
            if (_includeScope)
            {
                var logLevelString = GetLogLevelString(logLevel);
 
                // Example:
                // INFO: ConsoleApp.Program[10]
                //       Request received
 
                // category and event id
                _logBuilder.AppendFormat(string.Format("{0}: {1}[{2}]", logLevelString, logName, eventId));
                _logBuilder.AppendLine();
 
                // scope information
                messagePadding = new string(' ', logLevelString.Length + 2);
 
#if !NET45
                GetScopeInformation(_logBuilder, messagePadding);
#endif
            }
 
            if (!string.IsNullOrEmpty(message))
            {
                // add message padding
                if (_includeScope)
                {
                    message = $"{messagePadding}{message}".Replace(Environment.NewLine, $"{Environment.NewLine}{messagePadding}");
                }
 
                // write message
                _logBuilder.AppendLine(message);
            }
 
 
            // Example:
            // System.InvalidOperationException
            //    at Namespace.Class.Function() in File:line X
            if (exception != null)
            {
                // exception message
                _logBuilder.AppendLine(exception.FormatException(GetEnvironmentInformation(state)));
            }
 
            if (_logBuilder.Length > 0)
            {
                LogCallback?.Invoke(_logBuilder.ToString());
            }
 
            _logBuilder.Clear();
            if (_logBuilder.Capacity > 1024) _logBuilder.Capacity = 1024;
        }
 
        private NameValueCollection GetEnvironmentInformation<TState>(TState state)
        {
            var nv = state as NameValueCollection;
            if (nv == null) nv = new NameValueCollection();
 
#if !NET45
            // 收集环境变量信息
            nv["OS"] = RuntimeInformation.OSDescription;
            nv["Framework"] = RuntimeInformation.FrameworkDescription;
#endif
 
#if NETCore
            // 当前用户
            var userName = Configuration?.GetUserName();
            if (!string.IsNullOrEmpty(userName)) nv["UserName"] = userName;
 
            // 当前环境
            var env = Configuration?.GetEnvironmentName();
            if (!string.IsNullOrEmpty(env)) nv["EnvironmentName"] = env;
 
            // IIS Root 路径
            var iis = Configuration?.GetIISPath();
            if (!string.IsNullOrEmpty(iis)) nv["IISRootPath"] = iis;
 
            // VisualStudio Version
            var vs = Configuration?.GetVisualStudioVersion();
            if (!string.IsNullOrEmpty(vs)) nv["VSIDE"] = vs;
#endif
            return nv;
        }
 
        private static string GetLogLevelString(LogLevel logLevel)
        {
            switch (logLevel)
            {
                case LogLevel.Trace:
                    return "trce";
                case LogLevel.Debug:
                    return "dbug";
                case LogLevel.Information:
                    return "info";
                case LogLevel.Warning:
                    return "warn";
                case LogLevel.Error:
                    return "fail";
                case LogLevel.Critical:
                default:
                    return "crit";
            }
        }
    }
}