-
Notifications
You must be signed in to change notification settings - Fork 27
/
Logger.cs
232 lines (207 loc) · 7.87 KB
/
Logger.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
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
using DuetAPI.Commands;
using DuetAPI.ObjectModel;
using DuetControlServer.Files;
using Nito.AsyncEx;
using System;
using System.IO;
using System.Threading.Tasks;
namespace DuetControlServer.Utility
{
/// <summary>
/// Class for message logging
/// </summary>
public static class Logger
{
/// <summary>
/// Default log file for M929 in case no P parameter is specified
/// </summary>
public const string DefaultLogFile = "eventlog.txt";
/// <summary>
/// Logger instance
/// </summary>
private static readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
/// <summary>
/// Lock for the file
/// </summary>
private static readonly AsyncLock _lock = new AsyncLock();
/// <summary>
/// Filestream of the log file
/// </summary>
private static FileStream _fileStream;
/// <summary>
/// Writer for logging data
/// </summary>
private static StreamWriter _writer;
/// <summary>
/// Registration that is triggered when the log is supposed to be closed
/// </summary>
private static IDisposable _logCloseEvent;
/// <summary>
/// Start logging to a file
/// </summary>
/// <param name="filename">Filename to write to</param>
/// <param name="level">Requested log level</param>
/// <returns>Asynchronous task</returns>
public static async Task Start(string filename, LogLevel level)
{
using (await _lock.LockAsync(Program.CancellationToken))
{
// Close any open file
await StopInternal();
// Initialize access to the log file
string physicalFile = await FilePath.ToPhysicalAsync(filename, FileDirectory.System);
_fileStream = new FileStream(physicalFile, FileMode.Append, FileAccess.Write);
_writer = new StreamWriter(_fileStream) { AutoFlush = true };
_logCloseEvent = Program.CancellationToken.Register(() => Stop().Wait());
// Write the first line
await _writer.WriteLineAsync($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} Event logging started");
// Update the object model
using (await Model.Provider.AccessReadWriteAsync())
{
Model.Provider.Get.State.LogFile = filename;
Model.Provider.Get.State.LogLevel = level;
}
// Write event
_logger.Info("Event logging to {0} started", filename);
}
}
/// <summary>
/// Stop logging
/// </summary>
/// <returns>Asynchronous task</returns>
public static async Task Stop()
{
using (await _lock.LockAsync(Program.CancellationToken))
{
await StopInternal();
}
}
/// <summary>
/// Stop logging internally
/// </summary>
/// <returns>Asynchronous task</returns>
private static async Task StopInternal()
{
if (_writer != null)
{
await _writer.WriteLineAsync($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} Event logging stopped");
_writer.Close();
_writer = null;
_logger.Info("Event logging stopped");
}
if (_fileStream != null)
{
_fileStream.Close();
_fileStream = null;
}
if (!Program.CancellationToken.IsCancellationRequested)
{
if (_logCloseEvent != null)
{
_logCloseEvent.Dispose();
_logCloseEvent = null;
}
using (await Model.Provider.AccessReadWriteAsync())
{
Model.Provider.Get.State.LogFile = null;
Model.Provider.Get.State.LogLevel = LogLevel.Off;
}
}
}
/// <summary>
/// Write a message including timestamp to the log file
/// </summary>
/// <param name="msg">Message to log</param>
/// <returns>Asynchronous task</returns>
public static async Task Log(LogLevel level, Message msg)
{
using (await _lock.LockAsync(Program.CancellationToken))
{
if (level != LogLevel.Off && _writer != null && !string.IsNullOrWhiteSpace(msg.Content))
{
using (await Model.Provider.AccessReadOnlyAsync())
{
if (Model.Provider.Get.State.LogLevel == LogLevel.Off || level < Model.Provider.Get.State.LogLevel)
{
return;
}
}
try
{
await _writer.WriteAsync(msg.Time.ToString("yyyy-MM-dd HH:mm:ss "));
await _writer.WriteLineAsync(msg.ToString().TrimEnd());
}
catch (Exception e)
{
_logger.Error(e, "Failed to write to log file");
await StopInternal();
}
}
}
}
/// <summary>
/// Write a message including timestamp to the log file
/// </summary>
/// <param name="level">Log level</param>
/// <param name="type">Message type</param>
/// <param name="content">Message content</param>
public static Task Log(LogLevel level, MessageType type, string content) => Log(level, new Message(type, content));
/// <summary>
/// Write a message including timestamp to the log file
/// </summary>
/// <param name="type">Message type</param>
/// <param name="content">Message content</param>
public static Task Log(MessageType type, string content)
{
LogLevel level = (type == MessageType.Success) ? LogLevel.Info : LogLevel.Warn;
return Log(level, new Message(type, content));
}
/// <summary>
/// Write messages including timestamp to the log file
/// </summary>
/// <param name="result">Message list</param>
public static async Task Log(CodeResult result)
{
if (result != null)
{
foreach (Message msg in result)
{
LogLevel level = (msg.Type == MessageType.Success) ? LogLevel.Info : LogLevel.Warn;
await Log(level, msg);
}
}
}
/// <summary>
/// Log and output a message
/// </summary>
/// <param name="msg">Message</param>
/// <returns>Asynchronous task</returns>
public static async Task LogOutput(Message msg)
{
await Model.Provider.Output(msg);
await Log((msg.Type == MessageType.Success) ? LogLevel.Info : LogLevel.Warn, msg);
}
/// <summary>
/// Log and output a code result
/// </summary>
/// <param name="result">Code result</param>
/// <returns>Asynchronous task</returns>
public static async Task LogOutput(CodeResult result)
{
if (result != null)
{
foreach (Message msg in result)
{
await LogOutput(msg);
}
}
}
/// <summary>
/// Log and output a message
/// </summary>
/// <param name="type">Message type</param>
/// <param name="content">Message content</param>
/// <returns>Asynchronous task</returns>
public static Task LogOutput(MessageType type, string content) => LogOutput(new Message(type, content));
}
}