| | | 1 | | using System.Diagnostics; |
| | | 2 | | using ArturRios.Logging.Interfaces; |
| | | 3 | | using Microsoft.Extensions.DependencyInjection; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | |
| | | 6 | | namespace ArturRios.Logging.Adapter; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Bridges <see cref="ILogger"/> onto <see cref="IStateLogger"/>, so code written against |
| | | 10 | | /// Microsoft.Extensions.Logging reaches this library's loggers. |
| | | 11 | | /// </summary> |
| | | 12 | | /// <remarks> |
| | | 13 | | /// <para> |
| | | 14 | | /// Each call resolves <see cref="IStateLogger"/> from a fresh dependency injection scope, so a scoped |
| | | 15 | | /// dependency of the state logger is isolated per log entry. The correlation id therefore does not travel |
| | | 16 | | /// through the scope; it is read from the ambient <see cref="Activity"/> instead. |
| | | 17 | | /// </para> |
| | | 18 | | /// <para> |
| | | 19 | | /// <see cref="Activity"/> is the correlation primitive of the platform, not of any one hosting model: an |
| | | 20 | | /// ASP.NET Core request has one, and so does a worker, a console app or a test. Reading the id from there |
| | | 21 | | /// is what lets this library log correlated entries without depending on ASP.NET Core. |
| | | 22 | | /// </para> |
| | | 23 | | /// </remarks> |
| | | 24 | | /// <param name="services">The provider used to resolve the state logger.</param> |
| | | 25 | | /// <exception cref="ArgumentNullException"><paramref name="services"/> is <c>null</c>.</exception> |
| | 21 | 26 | | public class MicrosoftLoggerAdapter(IServiceProvider services) : ILogger |
| | | 27 | | { |
| | | 28 | | /// <summary> |
| | | 29 | | /// A correlation id set explicitly by a caller, overriding the ambient activity's. Held in an |
| | | 30 | | /// <see cref="AsyncLocal{T}"/> so it flows with the execution context — per request under a server, |
| | | 31 | | /// per logical operation anywhere else — rather than leaking across concurrent work. |
| | | 32 | | /// </summary> |
| | 1 | 33 | | private static readonly AsyncLocal<string?> Override = new(); |
| | | 34 | | |
| | 21 | 35 | | private readonly IServiceProvider _services = services ?? throw new ArgumentNullException(nameof(services)); |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Gets or sets the correlation id stamped on log entries. |
| | | 39 | | /// </summary> |
| | | 40 | | /// <value> |
| | | 41 | | /// The id set explicitly on this property, or the trace id of <see cref="Activity.Current"/> when none |
| | | 42 | | /// was set, or <c>null</c> when there is no ambient activity either. |
| | | 43 | | /// </value> |
| | | 44 | | /// <remarks> |
| | | 45 | | /// Setting it establishes the id for the current execution context and everything that flows from it. |
| | | 46 | | /// <c>ArturRios.Util.WebApi</c>'s <c>TraceActivityMiddleware</c> starts a W3C activity per request and |
| | | 47 | | /// derives its own trace id from exactly this activity, so under that middleware the value read here is |
| | | 48 | | /// the same one the middleware publishes — with no ASP.NET Core dependency on this side. |
| | | 49 | | /// </remarks> |
| | | 50 | | public string? TraceId |
| | | 51 | | { |
| | 16 | 52 | | get => Override.Value ?? Activity.Current?.TraceId.ToString(); |
| | 7 | 53 | | set => Override.Value = value; |
| | | 54 | | } |
| | | 55 | | |
| | | 56 | | /// <inheritdoc /> |
| | 0 | 57 | | public IDisposable BeginScope<TState>(TState state) where TState : notnull => NullScope.Instance; |
| | | 58 | | |
| | | 59 | | /// <inheritdoc /> |
| | 13 | 60 | | public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None; |
| | | 61 | | |
| | | 62 | | /// <inheritdoc /> |
| | | 63 | | public void Log<TState>( |
| | | 64 | | LogLevel logLevel, |
| | | 65 | | EventId eventId, |
| | | 66 | | TState state, |
| | | 67 | | Exception? exception, |
| | | 68 | | Func<TState, Exception?, string>? formatter) |
| | | 69 | | { |
| | 11 | 70 | | if (!IsEnabled(logLevel)) return; |
| | | 71 | | |
| | 11 | 72 | | var message = formatter != null ? formatter(state!, exception) : state?.ToString() ?? string.Empty; |
| | | 73 | | |
| | | 74 | | // Resolve the scoped IStateLogger (if not registered you'll get null) |
| | 11 | 75 | | using var scope = _services.CreateScope(); |
| | 11 | 76 | | var stateLogger = scope.ServiceProvider.GetService<IStateLogger>(); |
| | | 77 | | |
| | | 78 | | // Propagate the ambient correlation id, whether set explicitly or carried by the current activity. |
| | 11 | 79 | | if (stateLogger is not null && TraceId is { } ambientTraceId) |
| | | 80 | | { |
| | 4 | 81 | | stateLogger.TraceId = ambientTraceId; |
| | | 82 | | } |
| | | 83 | | |
| | 11 | 84 | | if (stateLogger is null) |
| | | 85 | | { |
| | | 86 | | // No IStateLogger registered — nothing to forward to |
| | 1 | 87 | | return; |
| | | 88 | | } |
| | | 89 | | |
| | | 90 | | // Enrich state with caller info if not present so StateLogger.ResolveCallerInfo can pick it up. |
| | 10 | 91 | | object? enrichedState = state; |
| | 10 | 92 | | if (!StateContainsCallerInfo(state)) |
| | | 93 | | { |
| | 8 | 94 | | var (filePath, memberName) = FindCallerFromStack(); |
| | 8 | 95 | | var kvList = new List<KeyValuePair<string, object>>(); |
| | | 96 | | |
| | 8 | 97 | | if (state is IEnumerable<KeyValuePair<string, object>> existingPairs) |
| | | 98 | | { |
| | 18 | 99 | | foreach (var kv in existingPairs) |
| | | 100 | | { |
| | 1 | 101 | | kvList.Add(kv); |
| | | 102 | | } |
| | | 103 | | } |
| | | 104 | | |
| | 8 | 105 | | kvList.Add(new KeyValuePair<string, object>("CallerFilePath", filePath)); |
| | 8 | 106 | | kvList.Add(new KeyValuePair<string, object>("CallerMemberName", memberName)); |
| | 8 | 107 | | kvList.Add(new KeyValuePair<string, object>("OriginalMessage", message)); |
| | | 108 | | |
| | 8 | 109 | | enrichedState = kvList.ToArray(); |
| | | 110 | | } |
| | | 111 | | |
| | 10 | 112 | | if (exception is not null) |
| | | 113 | | { |
| | 1 | 114 | | stateLogger.Exception(exception, enrichedState); |
| | | 115 | | } |
| | | 116 | | |
| | | 117 | | switch (logLevel) |
| | | 118 | | { |
| | | 119 | | case LogLevel.Trace: |
| | 0 | 120 | | stateLogger.Trace(message, enrichedState); |
| | 0 | 121 | | break; |
| | | 122 | | case LogLevel.Debug: |
| | 0 | 123 | | stateLogger.Debug(message, enrichedState); |
| | 0 | 124 | | break; |
| | | 125 | | case LogLevel.Information: |
| | 9 | 126 | | stateLogger.Info(message, enrichedState); |
| | 9 | 127 | | break; |
| | | 128 | | case LogLevel.Warning: |
| | 0 | 129 | | stateLogger.Warn(message, enrichedState); |
| | 0 | 130 | | break; |
| | | 131 | | case LogLevel.Error: |
| | 1 | 132 | | stateLogger.Error(message, enrichedState); |
| | 1 | 133 | | break; |
| | | 134 | | case LogLevel.Critical: |
| | 0 | 135 | | stateLogger.Critical(message, enrichedState); |
| | 0 | 136 | | break; |
| | | 137 | | case LogLevel.None: |
| | | 138 | | default: |
| | 0 | 139 | | throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); |
| | | 140 | | } |
| | 11 | 141 | | } |
| | | 142 | | |
| | | 143 | | private static bool StateContainsCallerInfo(object? state) |
| | | 144 | | { |
| | 10 | 145 | | if (state is not IEnumerable<KeyValuePair<string, object?>> pairs) |
| | | 146 | | { |
| | 0 | 147 | | return false; |
| | | 148 | | } |
| | | 149 | | |
| | 20 | 150 | | bool hasFile = false, hasMember = false; |
| | | 151 | | |
| | 28 | 152 | | foreach (var (k, v) in pairs) |
| | | 153 | | { |
| | 5 | 154 | | if (v is null) |
| | | 155 | | { |
| | | 156 | | continue; |
| | | 157 | | } |
| | | 158 | | |
| | 5 | 159 | | if (!hasFile && (string.Equals(k, "CallerFilePath", StringComparison.OrdinalIgnoreCase) || |
| | 5 | 160 | | string.Equals(k, "FilePath", StringComparison.OrdinalIgnoreCase) || |
| | 5 | 161 | | string.Equals(k, "callerFilePath", StringComparison.OrdinalIgnoreCase))) |
| | | 162 | | { |
| | 2 | 163 | | hasFile = true; |
| | | 164 | | } |
| | | 165 | | |
| | 5 | 166 | | if (!hasMember && (string.Equals(k, "CallerMemberName", StringComparison.OrdinalIgnoreCase) || |
| | 5 | 167 | | string.Equals(k, "MemberName", StringComparison.OrdinalIgnoreCase) || |
| | 5 | 168 | | string.Equals(k, "Method", StringComparison.OrdinalIgnoreCase) || |
| | 5 | 169 | | string.Equals(k, "callerMemberName", StringComparison.OrdinalIgnoreCase))) |
| | | 170 | | { |
| | 2 | 171 | | hasMember = true; |
| | | 172 | | } |
| | | 173 | | |
| | 7 | 174 | | if (hasFile && hasMember) return true; |
| | | 175 | | } |
| | | 176 | | |
| | 8 | 177 | | return false; |
| | 2 | 178 | | } |
| | | 179 | | |
| | | 180 | | private static (string filePath, string memberName) FindCallerFromStack() |
| | | 181 | | { |
| | | 182 | | try |
| | | 183 | | { |
| | 8 | 184 | | var st = new StackTrace(skipFrames: 1, fNeedFileInfo: false); |
| | | 185 | | |
| | 104 | 186 | | for (var i = 0; i < st.FrameCount; i++) |
| | | 187 | | { |
| | 52 | 188 | | var frame = st.GetFrame(i); |
| | 52 | 189 | | var method = frame?.GetMethod(); |
| | 52 | 190 | | if (method == null) continue; |
| | 52 | 191 | | var declaring = method.DeclaringType; |
| | 52 | 192 | | if (declaring == null) continue; |
| | | 193 | | |
| | 52 | 194 | | var ns = declaring.Namespace ?? string.Empty; |
| | | 195 | | |
| | | 196 | | // Skip known logging infrastructure namespaces so we find the real caller |
| | | 197 | | // ArturRios.Logging is this library's own namespace. The predecessor of this check named |
| | | 198 | | // ArturRios.Common.Logging, which no longer exists, so nothing here was ever skipped and the |
| | | 199 | | // frame reported as the caller was MicrosoftLoggerAdapter.Log itself. |
| | 52 | 200 | | if (ns.StartsWith("Microsoft.Extensions.Logging", StringComparison.Ordinal) || |
| | 52 | 201 | | ns.Equals("ArturRios.Logging", StringComparison.Ordinal) || |
| | 52 | 202 | | ns.StartsWith("ArturRios.Logging.", StringComparison.Ordinal) || |
| | 52 | 203 | | ns.StartsWith("System.", StringComparison.Ordinal)) |
| | | 204 | | { |
| | | 205 | | continue; |
| | | 206 | | } |
| | | 207 | | |
| | 8 | 208 | | var memberName = method.Name; |
| | 8 | 209 | | var filePath = declaring.FullName ?? declaring.Name; |
| | | 210 | | |
| | 8 | 211 | | return (filePath, memberName); |
| | | 212 | | } |
| | 0 | 213 | | } |
| | 0 | 214 | | catch |
| | | 215 | | { |
| | | 216 | | // swallow any errors and fall through to unknowns |
| | 0 | 217 | | } |
| | | 218 | | |
| | 0 | 219 | | return ("unknown", "unknown"); |
| | 8 | 220 | | } |
| | | 221 | | |
| | | 222 | | private class NullScope : IDisposable |
| | | 223 | | { |
| | 0 | 224 | | public static NullScope Instance { get; } = new(); |
| | 0 | 225 | | public void Dispose() { } |
| | | 226 | | } |
| | | 227 | | } |