forked from microsoft/component-detection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoggingEnricher.cs
80 lines (70 loc) · 2.62 KB
/
LoggingEnricher.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
namespace Microsoft.ComponentDetection.Orchestrator;
using Serilog.Core;
using Serilog.Events;
/// <summary>
/// Enriches log events with the log file path, derived from the command line arguments.
/// </summary>
public class LoggingEnricher : ILogEventEnricher
{
/// <summary>
/// The name of the log file path property.
/// </summary>
public const string LogFilePathPropertyName = "LogFilePath";
private string cachedLogFilePath;
private LogEventProperty cachedLogFilePathProperty;
/// <summary>
/// The name of the print stderr property.
/// </summary>
public const string PrintStderrPropertyName = "PrintStderr";
private bool? cachedPrintStderr;
private LogEventProperty cachedPrintStderrProperty;
/// <summary>
/// The path to the log file.
/// </summary>
public static string Path { get; set; } = string.Empty;
/// <summary>
/// <c>true</c> if logs should be printed to stderr; otherwise, <c>false</c>.
/// </summary>
public static bool PrintStderr { get; set; }
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
InvalidateLogEventProperty(
logEvent,
propertyFactory,
LogFilePathPropertyName,
Path,
ref this.cachedLogFilePathProperty,
ref this.cachedLogFilePath);
InvalidateLogEventProperty(
logEvent,
propertyFactory,
PrintStderrPropertyName,
PrintStderr,
ref this.cachedPrintStderrProperty,
ref this.cachedPrintStderr);
}
private static void InvalidateLogEventProperty<T>(
LogEvent logEvent,
ILogEventPropertyFactory propertyFactory,
string propertyName,
T propertyValue,
ref LogEventProperty cachedLogEventProperty,
ref T cachedPropertyValue)
{
// the settings might not have a value or we might not be within a command in which case
// we won't have the setting so a default value for will be required
LogEventProperty property;
if (cachedPropertyValue != null && propertyValue.Equals(cachedPropertyValue))
{
// hasn't changed, so let's use the cached property
property = cachedLogEventProperty;
}
else
{
// We've got a new value. Let's create a new property and cache it for future log events to use
cachedPropertyValue = propertyValue;
cachedLogEventProperty = property = propertyFactory.CreateProperty(propertyName, propertyValue);
}
logEvent.AddPropertyIfAbsent(property);
}
}