Skip to content

Instantly share code, notes, and snippets.

@qmfrederik
Last active November 22, 2018 16:41
Show Gist options
  • Save qmfrederik/d4901d104d2e270692420f1efe09dfd3 to your computer and use it in GitHub Desktop.
Save qmfrederik/d4901d104d2e270692420f1efe09dfd3 to your computer and use it in GitHub Desktop.
A request logger for ASP.NET Core
// Copyright (c) 2016 Quamotion bvba
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Samples.AspNetCore
{
/// <summary>
/// Provides extension methods to the <see cref="IApplicationBuilder"/> class which make it easy
/// to configure the <see cref="RequestLoggerMiddleware"/>.
/// </summary>
public static class RequestLoggerExtensions
{
/// <summary>
/// Adds the <see cref="RequestLoggerMiddleware"/> to the application.
/// </summary>
/// <param name="builder">
/// The application to which to add the <see cref="RequestLoggerMiddleware"/>.
/// </param>
/// <returns>
/// The updated <see cref="IApplicationBuilder"/>.
/// </returns>
public static IApplicationBuilder UseRequestLogger(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestLoggerMiddleware>();
}
}
/// <summary>
/// Logs all Web API requests.
/// </summary>
public class RequestLoggerMiddleware
{
/// <summary>
/// The next middleware in the call chain.
/// </summary>
private readonly RequestDelegate next;
/// <summary>
/// Initializes a new instance of the <see cref="RequestLoggerMiddleware"/> class.
/// </summary>
/// <param name="next">
/// The next middleware in the call chain.
/// </param>
public RequestLoggerMiddleware(RequestDelegate next)
{
this.next = next;
}
/// <summary>
/// Invokes the <see cref="RequestLoggerMiddleware"/> on the current <see cref="HttpContext"/>
/// </summary>
/// <param name="context">
/// The <see cref="HttpContext"/> in which to execute the middleware.
/// </param>
/// <returns>
/// A <see cref="Task"/> which represents the asynchronous operation.
/// </returns>
public async Task Invoke(HttpContext context)
{
var request = context.Request;
var path = request.Path;
ResponseLoggerStream responseLoggerStream = null;
RequestLoggerStream requestLoggerStream = null;
// Only trace JSON requests
bool shouldTrace =
context.Request.ContentType != null
&& context.Request.ContentType.StartsWith("application/json");
if (shouldTrace)
{
responseLoggerStream = new ResponseLoggerStream(context.Response.Body, ownsParent: false);
context.Response.Body = responseLoggerStream;
requestLoggerStream = new RequestLoggerStream(context.Request.Body, ownsParent: false);
context.Request.Body = requestLoggerStream;
}
try
{
// Invoke the other requests first.
await this.next.Invoke(context);
// The response type is available now, also filter on response type - only JSON
shouldTrace = shouldTrace
&& context.Response.ContentType != null
&& context.Response.ContentType.StartsWith("application/json");
if (shouldTrace)
{
MemoryStream requestTracerStream = requestLoggerStream.TracerStream;
var requestData = requestTracerStream.ToArray();
string requestContent = Encoding.UTF8.GetString(requestData);
// The requestContent string will contain the original request data
MemoryStream responseTracerStream = responseLoggerStream.TracerStream;
var responseData = responseTracerStream.ToArray();
string responseContent = Encoding.UTF8.GetString(responseData);
}
}
finally
{
// Remove any evidence of us having done tracing :). The stream to which the response is sent, and from which
// the requests are read, is the underlying TCP stream, and can be re-used for multiple requests. So we want
// to remove ourselves from the stream, to prevent the next request from still having our tracing attached
// to it.
if (responseLoggerStream != null)
{
context.Response.Body = responseLoggerStream.Inner;
responseLoggerStream.Dispose();
}
if (requestLoggerStream != null)
{
context.Request.Body = requestLoggerStream.Inner;
requestLoggerStream.Dispose();
}
}
}
}
/// <summary>
/// Traces the request data which is read by the server.
/// </summary>
public class RequestLoggerStream : Stream
{
private Stream inner;
private MemoryStream tracerStream;
private bool ownsParent;
/// <summary>
/// Initializes a new instance of the <see cref="RequestLoggerStream"/> class.
/// </summary>
/// <param name="inner">
/// The stream which is being wrapped.
/// </param>
/// <param name="ownsParent">
/// A value indicating whether the <paramref name="inner"/> should be disposed when the
/// <see cref="RequestLoggerStream"/> is disposed.
/// </param>
public RequestLoggerStream(Stream inner, bool ownsParent)
{
if (inner == null)
{
throw new ArgumentNullException(nameof(inner));
}
if (inner is RequestLoggerStream)
{
throw new InvalidOperationException("nesting of RequestLoggerStream objects is not allowed");
}
this.inner = inner;
this.tracerStream = new MemoryStream();
this.ownsParent = ownsParent;
}
/// <summary>
/// Gets a <see cref="MemoryStream"/>, which holds a copy of all data which was written to the inner
/// stream.
/// </summary>
public MemoryStream TracerStream
{
get
{
return this.tracerStream;
}
}
/// <summary>
/// Gets the <see cref="Stream"/> around which this <see cref="RequestLoggerStream"/> wraps.
/// </summary>
public Stream Inner
{
get { return this.inner; }
}
/// <inheritdoc/>
public override bool CanRead
{
get
{
return this.inner.CanRead;
}
}
/// <inheritdoc/>
public override bool CanSeek
{
get
{
return this.inner.CanSeek;
}
}
/// <inheritdoc/>
public override bool CanWrite
{
get
{
return this.inner.CanWrite;
}
}
/// <inheritdoc/>
public override long Length
{
get
{
return this.inner.Length;
}
}
/// <inheritdoc/>
public override long Position
{
get
{
return this.inner.Position;
}
set
{
this.inner.Position = value;
}
}
/// <inheritdoc/>
public override void Flush()
{
this.inner.Flush();
}
/// <inheritdoc/>
public override int Read(byte[] buffer, int offset, int count)
{
var read = this.inner.Read(buffer, offset, count);
this.tracerStream.Write(buffer, offset, read);
return read;
}
/// <inheritdoc/>
public override long Seek(long offset, SeekOrigin origin)
{
this.tracerStream.Seek(offset, origin);
return this.inner.Seek(offset, origin);
}
/// <inheritdoc/>
public override void SetLength(long value)
{
this.tracerStream.SetLength(value);
this.inner.SetLength(value);
}
/// <inheritdoc/>
public override void Write(byte[] buffer, int offset, int count)
{
this.tracerStream.Write(buffer, offset, count);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
this.tracerStream.Dispose();
if (this.ownsParent)
{
this.inner.Dispose();
}
base.Dispose(disposing);
}
}
/// <summary>
/// A <see cref="Stream"/> which wraps around another <see cref="Stream"/> and copies all data to a <see cref="MemoryStream"/>.
/// Used by the logging framework.
/// </summary>
public class ResponseLoggerStream : Stream
{
private readonly Stream inner;
private readonly MemoryStream tracerStream;
private readonly bool ownsParent;
/// <summary>
/// Initializes a new instance of the <see cref="ResponseLoggerStream"/> class.
/// </summary>
/// <param name="inner">
/// The stream which is being wrapped.
/// </param>
/// <param name="ownsParent">
/// A value indicating whether the <paramref name="inner"/> should be disposed when the
/// <see cref="RequestLoggerStream"/> is disposed.
/// </param>
public ResponseLoggerStream(Stream inner, bool ownsParent)
{
if (inner == null)
{
throw new ArgumentNullException(nameof(inner));
}
if (inner is ResponseLoggerStream)
{
throw new InvalidOperationException("nesting of ResponseLoggerStream objects is not allowed");
}
this.inner = inner;
this.tracerStream = new MemoryStream();
this.ownsParent = ownsParent;
}
/// <summary>
/// Gets a <see cref="MemoryStream"/>, which holds a copy of all data which was written to the inner
/// stream.
/// </summary>
public MemoryStream TracerStream
{
get
{
return this.tracerStream;
}
}
/// <summary>
/// Gets the <see cref="Stream"/> around which this <see cref="ResponseLoggerStream"/> wraps.
/// </summary>
public Stream Inner
{
get { return this.inner; }
}
/// <inheritdoc/>
public override bool CanRead
{
get
{
return this.inner.CanRead;
}
}
/// <inheritdoc/>
public override bool CanSeek
{
get
{
return this.inner.CanSeek;
}
}
/// <inheritdoc/>
public override bool CanWrite
{
get
{
return this.inner.CanWrite;
}
}
/// <inheritdoc/>
public override long Length
{
get
{
return this.inner.Length;
}
}
/// <inheritdoc/>
public override long Position
{
get
{
return this.inner.Position;
}
set
{
this.inner.Position = value;
}
}
/// <inheritdoc/>
public override void Flush()
{
this.inner.Flush();
}
/// <inheritdoc/>
public override int Read(byte[] buffer, int offset, int count)
{
this.tracerStream.Read(buffer, offset, count);
return this.inner.Read(buffer, offset, count);
}
/// <inheritdoc/>
public override long Seek(long offset, SeekOrigin origin)
{
this.tracerStream.Seek(offset, origin);
return this.inner.Seek(offset, origin);
}
/// <inheritdoc/>
public override void SetLength(long value)
{
this.tracerStream.SetLength(value);
this.inner.SetLength(value);
}
/// <inheritdoc/>
public override void Write(byte[] buffer, int offset, int count)
{
this.tracerStream.Write(buffer, offset, count);
this.inner.Write(buffer, offset, count);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
this.tracerStream.Dispose();
if (this.ownsParent)
{
this.inner.Dispose();
}
base.Dispose(disposing);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment