-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
LogProxy.cs
110 lines (99 loc) · 2.49 KB
/
LogProxy.cs
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
using System;
using System.IO;
using Microsoft.Extensions.Logging;
namespace StackExchange.Redis;
internal sealed class LogProxy : IDisposable
{
public static LogProxy TryCreate(TextWriter writer, ConfigurationOptions options)
=> writer == null && options?.Logger == null
? null
: new LogProxy(writer, options?.Logger);
private TextWriter _log;
private ILogger _logger;
internal static Action<string> NullWriter = _ => { };
public object SyncLock => this;
private LogProxy(TextWriter log, ILogger logger)
{
_log = log;
_logger = logger;
}
public void WriteLine()
{
if (_log != null) // note: double-checked
{
lock (SyncLock)
{
_log?.WriteLine();
}
}
}
public void LogInfo(string message = null)
{
var msg = $"{DateTime.UtcNow:HH:mm:ss.ffff}: {message}";
if (_log != null) // note: double-checked
{
lock (SyncLock)
{
_log?.WriteLine(msg);
}
}
_logger?.LogInformation(msg);
}
public void LogTrace(string message)
{
var msg = $"{DateTime.UtcNow:HH:mm:ss.ffff}: {message}";
if (_log != null) // note: double-checked
{
lock (SyncLock)
{
_log?.WriteLine(msg);
}
}
_logger?.LogTrace(msg);
}
public void LogError(Exception ex, string message)
{
var msg = $"{DateTime.UtcNow:HH:mm:ss.ffff}: {message}";
if (_log != null) // note: double-checked
{
lock (SyncLock)
{
_log?.WriteLine(msg);
}
}
_logger?.LogError(ex, msg);
}
public void WriteLine(string prefix, string message)
{
if (_log != null) // note: double-checked
{
lock (SyncLock)
{
_log?.WriteLine($"{DateTime.UtcNow:HH:mm:ss.ffff}: {prefix}{message}");
}
}
}
public override string ToString()
{
string s = null;
if (_log != null)
{
lock (SyncLock)
{
s = _log?.ToString();
}
}
return s ?? base.ToString();
}
public void Dispose()
{
if (_log != null) // note: double-checked
{
lock (SyncLock)
{
_log = null;
}
}
_logger = null;
}
}