-
Notifications
You must be signed in to change notification settings - Fork 42
/
FileLoggerExtensions.cs
199 lines (177 loc) · 10.4 KB
/
FileLoggerExtensions.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
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Debugging;
using Serilog.Extensions.Logging.File;
using Serilog.Formatting;
using Serilog.Formatting.Compact;
using Serilog.Formatting.Display;
namespace Microsoft.Extensions.Logging
{
/// <summary>
/// Extends <see cref="ILoggerFactory"/> with methods for configuring file logging.
/// </summary>
public static class FileLoggerExtensions
{
/// <summary>
/// Adds a file logger initialized from the supplied configuration section.
/// </summary>
/// <param name="loggerFactory">The logger factory.</param>
/// <param name="configuration">A configuration section with file parameters.</param>
/// <returns>A logger factory to allow further configuration.</returns>
public static ILoggerFactory AddFile(this ILoggerFactory loggerFactory, IConfigurationSection configuration)
{
if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory));
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
var config = configuration.Get<FileLoggingConfiguration>();
if (string.IsNullOrWhiteSpace(config.PathFormat))
{
SelfLog.WriteLine("Unable to add the file logger: no PathFormat was present in the configuration");
return loggerFactory;
}
var minimumLevel = GetMinimumLogLevel(configuration);
var levelOverrides = GetLevelOverrides(configuration);
return loggerFactory.AddFile(config.PathFormat, minimumLevel, levelOverrides, config.Json, config.FileSizeLimitBytes, config.RetainedFileCountLimit, config.OutputTemplate);
}
/// <summary>
/// Adds a file logger initialized from the supplied configuration section.
/// </summary>
/// <param name="loggerFactory">The logger factory.</param>
/// <param name="pathFormat">Filname to write. The filename may include {Date} to specify how the date portion of the
/// filename is calculated. May include environment variables.</param>
/// <param name="minimumLevel">The level below which events will be suppressed (the default is <see cref="LogLevel.Information"/>).</param>
/// <param name="levelOverrides">A dictionary mapping logger name prefixes to minimum logging levels.</param>
/// <param name="isJson">If true, the log file will be written in JSON format.</param>
/// <param name="fileSizeLimitBytes">The maximum size, in bytes, to which any single log file will be allowed to grow.
/// For unrestricted growth, pass null. The default is 1 GB.</param>
/// <param name="retainedFileCountLimit">The maximum number of log files that will be retained, including the current
/// log file. For unlimited retention, pass null. The default is 31.</param>
/// <param name="outputTemplate">The template used for formatting plain text log output. The default is
/// "{Timestamp:o} {RequestId,13} [{Level:u3}] {Message} ({EventId:x8}){NewLine}{Exception}"</param>
/// <returns>A logger factory to allow further configuration.</returns>
public static ILoggerFactory AddFile(
this ILoggerFactory loggerFactory,
string pathFormat,
LogLevel minimumLevel = LogLevel.Information,
IDictionary<string, LogLevel> levelOverrides = null,
bool isJson = false,
long? fileSizeLimitBytes = FileLoggingConfiguration.DefaultFileSizeLimitBytes,
int? retainedFileCountLimit = FileLoggingConfiguration.DefaultRetainedFileCountLimit,
string outputTemplate = FileLoggingConfiguration.DefaultOutputTemplate)
{
var logger = CreateLogger(pathFormat, minimumLevel, levelOverrides, isJson, fileSizeLimitBytes, retainedFileCountLimit, outputTemplate);
return loggerFactory.AddSerilog(logger, dispose: true);
}
/// <summary>
/// Adds a file logger initialized from the supplied configuration section.
/// </summary>
/// <param name="loggingBuilder">The logging builder.</param>
/// <param name="configuration">A configuration section with file parameters.</param>
/// <returns>The logging builder to allow further configuration.</returns>
public static ILoggingBuilder AddFile(this ILoggingBuilder loggingBuilder, IConfiguration configuration)
{
if (loggingBuilder == null) throw new ArgumentNullException(nameof(loggingBuilder));
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
var config = configuration.Get<FileLoggingConfiguration>();
if (string.IsNullOrWhiteSpace(config.PathFormat))
{
SelfLog.WriteLine("Unable to add the file logger: no PathFormat was present in the configuration");
return loggingBuilder;
}
var minimumLevel = GetMinimumLogLevel(configuration);
var levelOverrides = GetLevelOverrides(configuration);
return loggingBuilder.AddFile(config.PathFormat, minimumLevel, levelOverrides, config.Json, config.FileSizeLimitBytes, config.RetainedFileCountLimit, config.OutputTemplate);
}
/// <summary>
/// Adds a file logger initialized from the supplied configuration section.
/// </summary>
/// <param name="loggingBuilder">The logging builder.</param>
/// <param name="pathFormat">Filname to write. The filename may include {Date} to specify how the date portion of the
/// filename is calculated. May include environment variables.</param>
/// <param name="minimumLevel">The level below which events will be suppressed (the default is <see cref="LogLevel.Information"/>).</param>
/// <param name="levelOverrides">A dictionary mapping logger name prefixes to minimum logging levels.</param>
/// <param name="isJson">If true, the log file will be written in JSON format.</param>
/// <param name="fileSizeLimitBytes">The maximum size, in bytes, to which any single log file will be allowed to grow.
/// For unrestricted growth, pass null. The default is 1 GB.</param>
/// <param name="retainedFileCountLimit">The maximum number of log files that will be retained, including the current
/// log file. For unlimited retention, pass null. The default is 31.</param>
/// <param name="outputTemplate">The template used for formatting plain text log output. The default is
/// "{Timestamp:o} {RequestId,13} [{Level:u3}] {Message} ({EventId:x8}){NewLine}{Exception}"</param>
/// <returns>The logging builder to allow further configuration.</returns>
public static ILoggingBuilder AddFile(this ILoggingBuilder loggingBuilder,
string pathFormat,
LogLevel minimumLevel = LogLevel.Information,
IDictionary<string, LogLevel> levelOverrides = null,
bool isJson = false,
long? fileSizeLimitBytes = FileLoggingConfiguration.DefaultFileSizeLimitBytes,
int? retainedFileCountLimit = FileLoggingConfiguration.DefaultRetainedFileCountLimit,
string outputTemplate = FileLoggingConfiguration.DefaultOutputTemplate)
{
var logger = CreateLogger(pathFormat, minimumLevel, levelOverrides, isJson, fileSizeLimitBytes, retainedFileCountLimit, outputTemplate);
return loggingBuilder.AddSerilog(logger, dispose: true);
}
private static Serilog.Core.Logger CreateLogger(string pathFormat,
LogLevel minimumLevel,
IDictionary<string, LogLevel> levelOverrides,
bool isJson,
long? fileSizeLimitBytes,
int? retainedFileCountLimit,
string outputTemplate)
{
if (pathFormat == null) throw new ArgumentNullException(nameof(pathFormat));
if (outputTemplate == null) throw new ArgumentNullException(nameof(outputTemplate));
var formatter = isJson ?
(ITextFormatter)new RenderedCompactJsonFormatter() :
new MessageTemplateTextFormatter(outputTemplate, null);
var configuration = new LoggerConfiguration()
.MinimumLevel.Is(Conversions.MicrosoftToSerilogLevel(minimumLevel))
.Enrich.FromLogContext()
.WriteTo.Async(w => w.RollingFile(
formatter,
Environment.ExpandEnvironmentVariables(pathFormat),
fileSizeLimitBytes: fileSizeLimitBytes,
retainedFileCountLimit: retainedFileCountLimit,
shared: true,
flushToDiskInterval: TimeSpan.FromSeconds(2)));
if (!isJson)
{
configuration.Enrich.With<EventIdEnricher>();
}
foreach (var levelOverride in levelOverrides ?? new Dictionary<string, LogLevel>())
{
configuration.MinimumLevel.Override(levelOverride.Key, Conversions.MicrosoftToSerilogLevel(levelOverride.Value));
}
return configuration.CreateLogger();
}
private static LogLevel GetMinimumLogLevel(IConfiguration configuration)
{
var minimumLevel = LogLevel.Information;
var defaultLevel = configuration["LogLevel:Default"];
if (!string.IsNullOrWhiteSpace(defaultLevel))
{
if (!Enum.TryParse(defaultLevel, out minimumLevel))
{
SelfLog.WriteLine("The minimum level setting `{0}` is invalid", defaultLevel);
minimumLevel = LogLevel.Information;
}
}
return minimumLevel;
}
private static Dictionary<string, LogLevel> GetLevelOverrides(IConfiguration configuration)
{
var levelOverrides = new Dictionary<string, LogLevel>();
foreach (var overr in configuration.GetSection("LogLevel").GetChildren().Where(cfg => cfg.Key != "Default"))
{
if (!Enum.TryParse(overr.Value, out LogLevel value))
{
SelfLog.WriteLine("The level override setting `{0}` for `{1}` is invalid", overr.Value, overr.Key);
continue;
}
levelOverrides[overr.Key] = value;
}
return levelOverrides;
}
}
}