Saturday 30 July 2022

Log All Requests in ASP.NET Core API

Logging all incoming requests and the respose returned data in an API are useful way to diagnose any issues and monitor requests to an API. You can easily enable request logging in AP.NET Core 6 APIs, by setting the log level in app settings. Enabling such request reponse data logging will be useful in containerized APIs deployed to Kubernetes or even for APIs deployed to AzureApp Services  to diagnose and monitoring purposes. Let's look at how to enable request logging.

To test request loging lets create asample web api first by executing below command.

dotnet new webapi -f net6.0

A new web application will be created. 


If you run this application with dotnet run and test the weather forecast API available by default, or load swagger UI, you would not see any logs, other than startup information as shown below.



In the created web API you can see two files named appsettings.json and appsettings.Development.json. If you want to have request information logged only for development environment update the appsettings.Development.json with as below by updating Microsoft.AspNetCore category from Warning level to Information level. You can set the log level in appsettings.json for any non development environements.


Now, if you run the API and test you will see details logs appear for each request.



By setting log level to Trace you would be able to get more detailed information.


You can see more information on ASP.NET Core logging in the documentation here.

No comments:

Popular Posts