Is there anyway to log client ips with kestrel hosting? I specified DEBUG log level in app settings, but still it only shows server path being requested, not from whom.
I know client ip can be get from HttpContext structure within each api, but what I'd like is just logging it by the framework, so that I can save adding same function in each api.
dbug: Microsoft.AspNetCore.Server.Kestrel[1]
Connection id "0HL9L7IJ7JLIV" started.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://192.168.1.110:2180/ <====== it logs the server path
dbug: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[9]
AuthenticationScheme: Bearer was not authenticated.
dbug: Microsoft.AspNetCore.Routing.RouteBase[1]
Request successfully matched the route with name 'default' and template '{controller}/{action}'.
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action CH.Api.Controllers.HomeController.Index (CH)
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method CH.Controllers.HomeController.Index (CH) with arguments ((null)) - ModelState is Valid
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
...
dbug: Microsoft.AspNetCore.Server.Kestrel[9]
Connection id "0HL9L7IJ7JLIV" completed keep alive response.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 160.2879ms 200 text/plain; charset=utf-8
dbug: Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv[6]
Connection id "0HL9L7IJ7JLIV" received FIN.
dbug: Microsoft.AspNetCore.Server.Kestrel[10]
Connection id "0HL9L7IJ7JLIV" disconnecting.
dbug: Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv[7]
Connection id "0HL9L7IJ7JLIV" sending FIN.
dbug: Microsoft.AspNetCore.Server.Kestrel[2]
Connection id "0HL9L7IJ7JLIV" stopped.
Maybe you can create a custom middleware that logs each request with just four lines:
app.Use(async (context, next) =>
{
Console.WriteLine($"[{context.Connection.RemoteIpAddress}] | {context.Request.Path}");
await next.Invoke();
});
Output:
[127.0.0.1] | /
[127.0.0.1] | /About
[127.0.0.1] | /Post
Or replace context.Request.Path with context.Request.GetDisplayUrl()to see full URL:
[127.0.0.1] | http://127.0.0.1:5000/Post?id=1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With