Skip to content

Instantly share code, notes, and snippets.

@rmacfie
Last active May 14, 2016 11:21
Show Gist options
  • Save rmacfie/7b0bff25ae61500419030eb918b3f23b to your computer and use it in GitHub Desktop.
Save rmacfie/7b0bff25ae61500419030eb918b3f23b to your computer and use it in GitHub Desktop.
Simple request logging in Asp.Net Core, suitable for showing in the console while developing
using System;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Builder
{
public static class SimpleLogger
{
const string LOG_NAME = "MyProject.SimpleLogger";
const string LOG_FORMAT = "{0} | {1}ms | {2} | {3} {4}";
const string TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss:fff";
public static IApplicationBuilder UseSimpleLogger(this IApplicationBuilder app, ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger(LOG_NAME);
app.Use(async (context, next) =>
{
var stopwatch = Stopwatch.StartNew();
await next();
stopwatch.Stop();
var timestamp = DateTimeOffset.Now.ToString(TIMESTAMP_FORMAT);
var elapsed = stopwatch.ElapsedMilliseconds.ToString().PadLeft(5);
var status = context.Response.StatusCode;
var method = context.Request.Method;
var path = context.Request.Path + context.Request.QueryString;
if (status < 400)
logger.LogInformation(LOG_FORMAT, timestamp, elapsed, status, method, path);
else if (status < 500)
logger.LogWarning(LOG_FORMAT, timestamp, elapsed, status, method, path);
else
logger.LogError(LOG_FORMAT, timestamp, elapsed, status, method, path);
});
return app;
}
}
}
namespace MyProject
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
app.UseSimpleLogger(loggerFactory);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment