Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log HTTP requests with NLog

How to log HTTP Requests completely with NLog?

Here is how Fiddler catches it and I need something like this:

POST http://localhost/api/places/add HTTP/1.1
User-Agent: Fiddler
Host: localhost
Authorization: 375DF933413
Content-Length: 78
Content-Type: application/json

{ "location": { "lon": 35.005577, "lat": 48.435533}, "name": "n1" } 

I believe it should be possible to write some "magic" NLog layout expression.

like image 557
Alexander G Avatar asked Dec 05 '25 05:12

Alexander G


1 Answers

A simple approach:

public class LogHttpRequestAttribute : ActionFilterAttribute
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        _logger.Debug("action executing");

        base.OnActionExecuting(filterContext);
    }
}

usage:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    // Register global filter
    GlobalFilters.Filters.Add(new LogHttpRequestAttribute ());


}

To log the URL, use for ${aspnet-request:serverVariable=HTTP_URL} in you config, See wiki. Install NLog.Web for those layout renderers.

See NLog Wiki

like image 116
Julian Avatar answered Dec 07 '25 05:12

Julian