|
| 1 | +// Copyright 2019 Serilog Contributors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +using System; |
| 16 | +using System.Collections.Generic; |
| 17 | +using System.Diagnostics; |
| 18 | +using System.Linq; |
| 19 | +using System.Threading.Tasks; |
| 20 | +using Microsoft.AspNetCore.Http; |
| 21 | +using Microsoft.AspNetCore.Http.Features; |
| 22 | +using Serilog.Events; |
| 23 | +using Serilog.Extensions.Hosting; |
| 24 | +using Serilog.Parsing; |
| 25 | + |
| 26 | +namespace Serilog.AspNetCore |
| 27 | +{ |
| 28 | + class RequestLoggingMiddleware |
| 29 | + { |
| 30 | + readonly RequestDelegate _next; |
| 31 | + readonly DiagnosticContext _diagnosticContext; |
| 32 | + readonly MessageTemplate _messageTemplate; |
| 33 | + readonly int _messageTemplatePlaceholderCount; |
| 34 | + |
| 35 | + public RequestLoggingMiddleware(RequestDelegate next, DiagnosticContext diagnosticContext, RequestLoggingOptions options) |
| 36 | + { |
| 37 | + if (options == null) throw new ArgumentNullException(nameof(options)); |
| 38 | + _next = next ?? throw new ArgumentNullException(nameof(next)); |
| 39 | + _diagnosticContext = diagnosticContext ?? throw new ArgumentNullException(nameof(diagnosticContext)); |
| 40 | + |
| 41 | + _messageTemplate = new MessageTemplateParser().Parse(options.MessageTemplate); |
| 42 | + _messageTemplatePlaceholderCount = _messageTemplate.Tokens.OfType<PropertyToken>().Count(); |
| 43 | + } |
| 44 | + |
| 45 | + // ReSharper disable once UnusedMember.Global |
| 46 | + public async Task Invoke(HttpContext httpContext) |
| 47 | + { |
| 48 | + if (httpContext == null) throw new ArgumentNullException(nameof(httpContext)); |
| 49 | + |
| 50 | + var start = Stopwatch.GetTimestamp(); |
| 51 | + |
| 52 | + var collector = _diagnosticContext.BeginCollection(); |
| 53 | + try |
| 54 | + { |
| 55 | + await _next(httpContext); |
| 56 | + var elapsedMs = GetElapsedMilliseconds(start, Stopwatch.GetTimestamp()); |
| 57 | + var statusCode = httpContext.Response.StatusCode; |
| 58 | + LogCompletion(httpContext, collector, statusCode, elapsedMs, null); |
| 59 | + } |
| 60 | + catch (Exception ex) |
| 61 | + // Never caught, because `LogCompletion()` returns false. This ensures e.g. the developer exception page is still |
| 62 | + // shown, although it does also mean we see a duplicate "unhandled exception" event from ASP.NET Core. |
| 63 | + when (LogCompletion(httpContext, collector, 500, GetElapsedMilliseconds(start, Stopwatch.GetTimestamp()), ex)) |
| 64 | + { |
| 65 | + } |
| 66 | + finally |
| 67 | + { |
| 68 | + collector.Dispose(); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + bool LogCompletion(HttpContext httpContext, DiagnosticContextCollector collector, int statusCode, double elapsedMs, Exception ex) |
| 73 | + { |
| 74 | + var level = statusCode > 499 ? LogEventLevel.Error : LogEventLevel.Information; |
| 75 | + |
| 76 | + if (!Log.IsEnabled(level)) return false; |
| 77 | + |
| 78 | + if (!collector.TryComplete(out var properties)) |
| 79 | + properties = new List<LogEventProperty>(); |
| 80 | + |
| 81 | + properties.Capacity = properties.Count + _messageTemplatePlaceholderCount; |
| 82 | + |
| 83 | + // Last-in (rightly) wins... |
| 84 | + properties.Add(new LogEventProperty("RequestMethod", new ScalarValue(httpContext.Request.Method))); |
| 85 | + properties.Add(new LogEventProperty("RequestPath", new ScalarValue(GetPath(httpContext)))); |
| 86 | + properties.Add(new LogEventProperty("StatusCode", new ScalarValue(statusCode))); |
| 87 | + properties.Add(new LogEventProperty("Elapsed", new ScalarValue(elapsedMs))); |
| 88 | + var evt = new LogEvent(DateTimeOffset.Now, level, ex, _messageTemplate, properties); |
| 89 | + Log.Write(evt); |
| 90 | + |
| 91 | + return false; |
| 92 | + } |
| 93 | + |
| 94 | + static double GetElapsedMilliseconds(long start, long stop) |
| 95 | + { |
| 96 | + return (stop - start) * 1000 / (double)Stopwatch.Frequency; |
| 97 | + } |
| 98 | + |
| 99 | + static string GetPath(HttpContext httpContext) |
| 100 | + { |
| 101 | + return httpContext.Features.Get<IHttpRequestFeature>()?.RawTarget ?? httpContext.Request.Path.ToString(); |
| 102 | + } |
| 103 | + } |
| 104 | +} |
0 commit comments