-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFileLogger.cs
More file actions
88 lines (56 loc) · 2.57 KB
/
FileLogger.cs
File metadata and controls
88 lines (56 loc) · 2.57 KB
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
using System;
using System.IO;
namespace Gsemac.IO.Logging {
public class FileLogger :
SynchronizedLoggerBase {
// Public members
public FileLogger() :
this(LoggerOptions.Default) {
}
public FileLogger(ILoggerOptions options) :
base(new LoggerOptions(options) { Enabled = false }) {
// Headers are written as soon as the logger is instantiated, but we haven't set the "options" member yet, so we won't have the right path.
// The logger is temporarily disabled, and then re-enabled after assigning to the member, which causes the headers to be written to the correct path.
this.options = options;
Enabled = options.Enabled;
}
public FileLogger(string fileName) :
this(CreateLoggerOptions(fileName)) {
}
public FileLogger(string fileName, ILoggerOptions options) :
this(CreateLoggerOptions(fileName, options)) {
}
// Protected members
protected override void Log(ILogMessage message, string formattedMessage) {
CreateLogFile();
string fullLogFilePath = logFilePath;
if (!string.IsNullOrWhiteSpace(options.DirectoryPath))
fullLogFilePath = Path.Combine(options.DirectoryPath, fullLogFilePath);
File.AppendAllText(fullLogFilePath, formattedMessage);
}
// Private members
private readonly ILoggerOptions options;
private string logFilePath = string.Empty;
private void CreateLogDirectory() {
if (!string.IsNullOrWhiteSpace(options.DirectoryPath) && !Directory.Exists(options.DirectoryPath))
Directory.CreateDirectory(options.DirectoryPath);
}
private void CreateLogFile() {
CreateLogDirectory();
if (string.IsNullOrWhiteSpace(logFilePath))
logFilePath = options.FileNameFormatter.GetFileName();
}
private static ILoggerOptions CreateLoggerOptions(string fileName) {
return CreateLoggerOptions(fileName, LoggerOptions.Default);
}
private static ILoggerOptions CreateLoggerOptions(string fileName, ILoggerOptions options) {
if (fileName is null)
throw new ArgumentNullException(nameof(fileName));
if (options is null)
throw new ArgumentNullException(nameof(options));
return new LoggerOptions(options) {
FileNameFormatter = new LogFileNameFormatter(fileName),
};
}
}
}