| | | 1 | | using System.Diagnostics; |
| | | 2 | | using ArturRios.Logging.Interfaces; |
| | | 3 | | using Microsoft.AspNetCore.Http; |
| | | 4 | | using Microsoft.Extensions.DependencyInjection; |
| | | 5 | | using Microsoft.Extensions.Logging; |
| | | 6 | | |
| | | 7 | | namespace ArturRios.Logging.Adapter; |
| | | 8 | | |
| | 9 | 9 | | public class MicrosoftLoggerAdapter(IServiceProvider services) : ILogger |
| | | 10 | | { |
| | 9 | 11 | | private readonly IServiceProvider _services = services ?? throw new ArgumentNullException(nameof(services)); |
| | | 12 | | |
| | | 13 | | // Expose TraceId by reading/writing the current HttpContext item (if available) |
| | | 14 | | public string? TraceId |
| | | 15 | | { |
| | | 16 | | get |
| | 4 | 17 | | { |
| | 4 | 18 | | var accessor = _services.GetService<IHttpContextAccessor>(); |
| | 4 | 19 | | return accessor?.HttpContext?.Items["TraceId"] as string; |
| | 4 | 20 | | } |
| | | 21 | | set |
| | 3 | 22 | | { |
| | 3 | 23 | | var accessor = _services.GetService<IHttpContextAccessor>(); |
| | | 24 | | |
| | 3 | 25 | | accessor?.HttpContext?.Items["TraceId"] = value; |
| | 3 | 26 | | } |
| | | 27 | | } |
| | | 28 | | |
| | | 29 | | /// <inheritdoc /> |
| | 0 | 30 | | public IDisposable BeginScope<TState>(TState state) where TState : notnull => NullScope.Instance; |
| | | 31 | | |
| | | 32 | | /// <inheritdoc /> |
| | 4 | 33 | | public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None; |
| | | 34 | | |
| | | 35 | | /// <inheritdoc /> |
| | | 36 | | public void Log<TState>( |
| | | 37 | | LogLevel logLevel, |
| | | 38 | | EventId eventId, |
| | | 39 | | TState state, |
| | | 40 | | Exception? exception, |
| | | 41 | | Func<TState, Exception?, string>? formatter) |
| | 2 | 42 | | { |
| | 2 | 43 | | if (!IsEnabled(logLevel)) return; |
| | | 44 | | |
| | 2 | 45 | | var message = formatter != null ? formatter(state!, exception) : state?.ToString() ?? string.Empty; |
| | | 46 | | |
| | | 47 | | // Resolve the scoped IStateLogger (if not registered you'll get null) |
| | 2 | 48 | | using var scope = _services.CreateScope(); |
| | 2 | 49 | | var stateLogger = scope.ServiceProvider.GetService<IStateLogger>(); |
| | 2 | 50 | | var httpAccessor = scope.ServiceProvider.GetService<IHttpContextAccessor>(); |
| | | 51 | | |
| | | 52 | | // Propagate TraceId from HttpContext (middleware should set this per request) |
| | 2 | 53 | | if (stateLogger is not null && httpAccessor?.HttpContext?.Items["TraceId"] is string httpTrace) |
| | 1 | 54 | | { |
| | 1 | 55 | | stateLogger.TraceId = httpTrace; |
| | 1 | 56 | | } |
| | | 57 | | |
| | 2 | 58 | | if (stateLogger is null) |
| | 0 | 59 | | { |
| | | 60 | | // No IStateLogger registered — nothing to forward to |
| | 0 | 61 | | return; |
| | | 62 | | } |
| | | 63 | | |
| | | 64 | | // Enrich state with caller info if not present so StateLogger.ResolveCallerInfo can pick it up. |
| | 2 | 65 | | object? enrichedState = state; |
| | 2 | 66 | | if (!StateContainsCallerInfo(state)) |
| | 2 | 67 | | { |
| | 2 | 68 | | var (filePath, memberName) = FindCallerFromStack(); |
| | 2 | 69 | | var kvList = new List<KeyValuePair<string, object>>(); |
| | | 70 | | |
| | 2 | 71 | | if (state is IEnumerable<KeyValuePair<string, object>> existingPairs) |
| | 2 | 72 | | { |
| | 8 | 73 | | foreach (var kv in existingPairs) |
| | 1 | 74 | | { |
| | 1 | 75 | | kvList.Add(kv); |
| | 1 | 76 | | } |
| | 2 | 77 | | } |
| | | 78 | | |
| | 2 | 79 | | kvList.Add(new KeyValuePair<string, object>("CallerFilePath", filePath)); |
| | 2 | 80 | | kvList.Add(new KeyValuePair<string, object>("CallerMemberName", memberName)); |
| | 2 | 81 | | kvList.Add(new KeyValuePair<string, object>("OriginalMessage", message)); |
| | | 82 | | |
| | 2 | 83 | | enrichedState = kvList.ToArray(); |
| | 2 | 84 | | } |
| | | 85 | | |
| | 2 | 86 | | if (exception is not null) |
| | 1 | 87 | | { |
| | 1 | 88 | | stateLogger.Exception(exception, enrichedState); |
| | 1 | 89 | | } |
| | | 90 | | |
| | 2 | 91 | | switch (logLevel) |
| | | 92 | | { |
| | | 93 | | case LogLevel.Trace: |
| | 0 | 94 | | stateLogger.Trace(message, enrichedState); |
| | 0 | 95 | | break; |
| | | 96 | | case LogLevel.Debug: |
| | 0 | 97 | | stateLogger.Debug(message, enrichedState); |
| | 0 | 98 | | break; |
| | | 99 | | case LogLevel.Information: |
| | 1 | 100 | | stateLogger.Info(message, enrichedState); |
| | 1 | 101 | | break; |
| | | 102 | | case LogLevel.Warning: |
| | 0 | 103 | | stateLogger.Warn(message, enrichedState); |
| | 0 | 104 | | break; |
| | | 105 | | case LogLevel.Error: |
| | 1 | 106 | | stateLogger.Error(message, enrichedState); |
| | 1 | 107 | | break; |
| | | 108 | | case LogLevel.Critical: |
| | 0 | 109 | | stateLogger.Critical(message, enrichedState); |
| | 0 | 110 | | break; |
| | | 111 | | case LogLevel.None: |
| | | 112 | | default: |
| | 0 | 113 | | throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); |
| | | 114 | | } |
| | 4 | 115 | | } |
| | | 116 | | |
| | | 117 | | private static bool StateContainsCallerInfo(object? state) |
| | 2 | 118 | | { |
| | 2 | 119 | | if (state is not IEnumerable<KeyValuePair<string, object?>> pairs) |
| | 0 | 120 | | { |
| | 0 | 121 | | return false; |
| | | 122 | | } |
| | | 123 | | |
| | 4 | 124 | | bool hasFile = false, hasMember = false; |
| | | 125 | | |
| | 8 | 126 | | foreach (var (k, v) in pairs) |
| | 1 | 127 | | { |
| | 1 | 128 | | if (v is null) |
| | 0 | 129 | | { |
| | 0 | 130 | | continue; |
| | | 131 | | } |
| | | 132 | | |
| | 1 | 133 | | if (!hasFile && (string.Equals(k, "CallerFilePath", StringComparison.OrdinalIgnoreCase) || |
| | 1 | 134 | | string.Equals(k, "FilePath", StringComparison.OrdinalIgnoreCase) || |
| | 1 | 135 | | string.Equals(k, "callerFilePath", StringComparison.OrdinalIgnoreCase))) |
| | 0 | 136 | | { |
| | 0 | 137 | | hasFile = true; |
| | 0 | 138 | | } |
| | | 139 | | |
| | 1 | 140 | | if (!hasMember && (string.Equals(k, "CallerMemberName", StringComparison.OrdinalIgnoreCase) || |
| | 1 | 141 | | string.Equals(k, "MemberName", StringComparison.OrdinalIgnoreCase) || |
| | 1 | 142 | | string.Equals(k, "Method", StringComparison.OrdinalIgnoreCase) || |
| | 1 | 143 | | string.Equals(k, "callerMemberName", StringComparison.OrdinalIgnoreCase))) |
| | 0 | 144 | | { |
| | 0 | 145 | | hasMember = true; |
| | 0 | 146 | | } |
| | | 147 | | |
| | 1 | 148 | | if (hasFile && hasMember) return true; |
| | 1 | 149 | | } |
| | | 150 | | |
| | 2 | 151 | | return false; |
| | 2 | 152 | | } |
| | | 153 | | |
| | | 154 | | private static (string filePath, string memberName) FindCallerFromStack() |
| | 2 | 155 | | { |
| | | 156 | | try |
| | 2 | 157 | | { |
| | 2 | 158 | | var st = new StackTrace(skipFrames: 1, fNeedFileInfo: false); |
| | | 159 | | |
| | 4 | 160 | | for (var i = 0; i < st.FrameCount; i++) |
| | 2 | 161 | | { |
| | 2 | 162 | | var frame = st.GetFrame(i); |
| | 2 | 163 | | var method = frame?.GetMethod(); |
| | 2 | 164 | | if (method == null) continue; |
| | 2 | 165 | | var declaring = method.DeclaringType; |
| | 2 | 166 | | if (declaring == null) continue; |
| | | 167 | | |
| | 2 | 168 | | var ns = declaring.Namespace ?? string.Empty; |
| | | 169 | | |
| | | 170 | | // Skip known logging infrastructure namespaces so we find the real caller |
| | 2 | 171 | | if (ns.StartsWith("Microsoft.Extensions.Logging", StringComparison.Ordinal) || |
| | 2 | 172 | | ns.StartsWith("ArturRios.Common.Logging", StringComparison.Ordinal) || |
| | 2 | 173 | | ns.StartsWith("System.", StringComparison.Ordinal)) |
| | 0 | 174 | | { |
| | 0 | 175 | | continue; |
| | | 176 | | } |
| | | 177 | | |
| | 2 | 178 | | var memberName = method.Name; |
| | 2 | 179 | | var filePath = declaring.FullName ?? declaring.Name; |
| | | 180 | | |
| | 2 | 181 | | return (filePath, memberName); |
| | | 182 | | } |
| | 0 | 183 | | } |
| | 0 | 184 | | catch |
| | 0 | 185 | | { |
| | | 186 | | // swallow any errors and fall through to unknowns |
| | 0 | 187 | | } |
| | | 188 | | |
| | 0 | 189 | | return ("unknown", "unknown"); |
| | 2 | 190 | | } |
| | | 191 | | |
| | | 192 | | private class NullScope : IDisposable |
| | | 193 | | { |
| | 0 | 194 | | public static NullScope Instance { get; } = new(); |
| | 0 | 195 | | public void Dispose() { } |
| | | 196 | | } |
| | | 197 | | } |