OWIN
using System.Configuration;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Owin;
using Serilog.Context;
using Serilog.Core.Enrichers;
namespace Readify.Logging
{
public class RequestLoggingMiddleware : OwinMiddleware
{
private string _environment;
public RequestLoggingMiddleware(OwinMiddleware next) : base(next)
{
_environment = ConfigurationManager.AppSettings["Octopus.Environment.Name"];
}
public override Task Invoke(IOwinContext context)
{
var sw = new Stopwatch();
sw.Start();
using (LogContext.PushProperties(
new PropertyEnricher("Environment", _environment),
new PropertyEnricher("HttpRequestId", context.Environment[HttpRequestIdMiddleware.OwinRequestIdKey]),
new PropertyEnricher("HttpRequestClientHostIP", context.Request.RemoteIpAddress)))
{
try
{
return Next.Invoke(context);
}
finally
{
sw.Stop();
if (context.Response.StatusCode >= 400)
{
Serilog.Log.Logger.Warning(
"HTTP {Method} {RawUrl} responded {StatusCode} in {ElapsedMilliseconds}ms",
context.Request.Method, context.Request.Uri.PathAndQuery, context.Response.StatusCode,
sw.ElapsedMilliseconds);
}
else
{
Serilog.Log.Logger.Information(
"HTTP {Method} {RawUrl} responded {StatusCode} in {ElapsedMilliseconds}ms",
context.Request.Method, context.Request.Uri.PathAndQuery, context.Response.StatusCode,
sw.ElapsedMilliseconds);
}
}
}
}
}
}
namespace Readify.OWin
{
public class HttpRequestIdMiddleware : OwinMiddleware
{
public const string OwinRequestIdKey = "owin.RequestId";
public HttpRequestIdMiddleware(OwinMiddleware next) : base(next)
{
}
public override Task Invoke(IOwinContext context)
{
if (!context.Environment.ContainsKey(OwinRequestIdKey))
{
context.Environment.Add(OwinRequestIdKey, Guid.NewGuid());
}
return Next.Invoke(context);
}
}
}