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
#if !NET45
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
#else
using System.IO;
#endif
using System;
using System.Collections.Specialized;
 
namespace Prow.Logging
{
    /// <summary>
    /// 异常管理操作类
    /// </summary>
    public static class ExceptionManager
    {
#if !NET45
        private static IServiceCollection? _services;
        private static Lazy<ILogger> _logger = new Lazy<ILogger>(() => _services.BuildServiceProvider().GetRequiredService<ILogger<Logger>>());
 
        /// <summary>
        /// 异常日志注入时调用
        /// </summary>
        /// <param name="services">IServiceCollection 实例</param>
        internal static void RegisterExceptionManager(this IServiceCollection services) => _services = services;
 
        /// <summary>
        /// 记录日志方法
        /// </summary>
        /// <param name="ex">Exception 实例</param>
        /// <param name="nv">日志附属信息</param>
        public static void Publish(Exception ex, NameValueCollection? nv = null) => _logger.Value.Log(LogLevel.Error, 0, nv, ex, (n, e) => string.Empty);
#else
        private static FileLoggerProvider _provider = new FileLoggerProvider(new FileLoggerOptions() { FileName = $"Error{Path.DirectorySeparatorChar}Error.log" });
        private static Lazy<ILogger> _logger = new Lazy<ILogger>(() => _provider.CreateLogger(nameof(ExceptionManager)));
 
        /// <summary>
        /// 记录日志方法
        /// </summary>
        /// <param name="ex">Exception 实例</param>
        /// <param name="nv">日志附属信息</param>
        public static void Publish(Exception ex, NameValueCollection? nv = null) => _logger.Value.Log(LogLevel.Error, ex.FormatException(nv));
 
        /// <summary>
        /// 强制输出到日志文件
        /// </summary>
        public static void Flush() => _provider.Flush();
#endif
    }
}