|
1 | 1 | // Copyright (c) Microsoft Corporation.
|
2 | 2 | // Licensed under the MIT License.
|
3 | 3 |
|
| 4 | +using PSRule.Options; |
| 5 | + |
4 | 6 | namespace PSRule.Runtime;
|
5 | 7 |
|
6 | 8 | /// <summary>
|
@@ -76,11 +78,45 @@ public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId,
|
76 | 78 | logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter);
|
77 | 79 | }
|
78 | 80 |
|
| 81 | + /// <summary> |
| 82 | + /// Log a diagnostic message with an <see cref="ExecutionActionPreference"/>. |
| 83 | + /// The log level is determined by the action preference. |
| 84 | + /// </summary> |
| 85 | + /// <param name="logger">A valid <see cref="ILogger"/> instance.</param> |
| 86 | + /// <param name="actionPreference">The action preference of the diagnostic message.</param> |
| 87 | + /// <param name="eventId">An event identifier for the diagnostic message.</param> |
| 88 | + /// <param name="exception">An optional exception which the diagnostic message is related to.</param> |
| 89 | + /// <param name="message">The format message text.</param> |
| 90 | + /// <param name="args">Additional arguments to use within the format message.</param> |
| 91 | + public static void Log(this ILogger logger, ExecutionActionPreference actionPreference, EventId eventId, Exception? exception, string? message, params object?[] args) |
| 92 | + { |
| 93 | + var logLevel = GetLogLevel(actionPreference); |
| 94 | + if (logger == null || !logger.IsEnabled(logLevel)) |
| 95 | + return; |
| 96 | + |
| 97 | + logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter); |
| 98 | + } |
| 99 | + |
79 | 100 | /// <summary>
|
80 | 101 | /// Format log messages with values.
|
81 | 102 | /// </summary>
|
82 | 103 | private static string MessageFormatter(FormattedLogValues state, Exception? error)
|
83 | 104 | {
|
84 | 105 | return state.ToString();
|
85 | 106 | }
|
| 107 | + |
| 108 | + /// <summary> |
| 109 | + /// Convert an <see cref="ExecutionActionPreference"/> to a <see cref="LogLevel"/>. |
| 110 | + /// </summary> |
| 111 | + private static LogLevel GetLogLevel(ExecutionActionPreference actionPreference) |
| 112 | + { |
| 113 | + return actionPreference switch |
| 114 | + { |
| 115 | + ExecutionActionPreference.Ignore => LogLevel.None, |
| 116 | + ExecutionActionPreference.Error => LogLevel.Error, |
| 117 | + ExecutionActionPreference.Warn => LogLevel.Warning, |
| 118 | + ExecutionActionPreference.Debug => LogLevel.Debug, |
| 119 | + _ => LogLevel.None, |
| 120 | + }; |
| 121 | + } |
86 | 122 | }
|
0 commit comments