Last active
May 14, 2016 11:21
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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