I was developing a new ASP.NET Core Web API with .NET 5.0 target framework using Visual Studio 2019, and I needed to write some logs into text file for my application. So, this is what I found at the time.
Install the Microsoft.Extensions.Logging.AzureAppServices NuGet Package
In Visual Studio, download the NuGet package below to the web api project.
Add ILogger to your Controller
Add ILogger parameter for each of the controller's constructor. The namespace of the controller will then be automatically included for each line of log written.
private ILogger<ValuesController> logger;
public ValuesController(ILogger<ValuesController> logger)
{
this.logger = logger;
}
Simply call LogInformation, LogWarning, LogError, or the desired log level where you see fit.
logger.LogInformation("Some information logged here.");
Configure the appsettings.json file
In the appsettings.json file, add new entry "AzureAppServicesBlob" as the log provider within the Logging section. Within the LogLevel section, add a new entry for your project root namespace as name and the desired log level as value.
The available log level at the time of writing is as per below:
Trace = 0
Debug = 1
Information = 2
Warning = 3
Error = 4
Critical = 5
None = 6
All of higher log levels from the selected minimum log level will be written to the log files. For example, Information log level will include Warning, Error, and Critical log entries. In below example, I am only interested in the Error log level and above for anything from Microsoft, and Information log level and above for my web api.
More reading is available here
Configure the App Service Logs of the App Service in Azure.
Navigate to the App Service Logs of the App Service, then enable Application Logging (blob). Here I set the default logging level to Error level. The appsettings.json will override the default log level for the specific component configured (eg. Microsoft, or my web api).
Select the Storage container where to store the log files, and set how long to keep in days.
Publish to Azure and test the logging
Publish the project to Azure App Service.
Make web request to the controller to test the logging. In this demo project, I could simply browse to the Url to execute a GET request for a quick demo.
Navigate to the Azure Storage configured for the logging. The log files will be neatly organised by the date and time components.
To view the content, simply download and open in a text editor.
Hope this is useful.
Comments