Logging helps you diagnose problems and whilst dumping output to the console is suitable for most instances, there might be situations where you don’t have the option of surfacing logging output to Application Insights in Azure.
Logging to an external file can help.
In this short post you will see how to implement logging to JSON files using .NET 6 and Serilog.Extensions.Logging.File package.
Serilog.Extensions.Logging.File
This package makes it possible for you to add file logging in a few lines of code to ASP.NET Core applications.
Find it out more about this package here.
Program.cs
A typical web API template in VS2022 will create the following code
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
After adding a reference to the Serilog.Extensions.Logging.File NuGet package, you can add the following code to Program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging((_, builder) => { builder.ClearProviders(); builder.AddConsole(); builder.AddFile("logs/app-{Date}.json", isJson: true); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
The will setup file logging in JSON format. All log files will be saved to the logs folder using the naming convention app-yyyymmdd.json.
Controller
Logging is supported and implement by using dependency injection in the web API controller. The instance is passed into the constructor and used to set a private variable.
For example:
[ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } }
After doing this, you can use your instance of _logger to perform logging within your controller. For example:
[HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { _logger.LogInformation("Entered GetWeatherForecast"); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }).ToArray(); }
Testing and Example Output
The web API can be tested by accessing the Swagger page:
When we invoke the API, a new logs directory is created. The file for the current day is also created:
The code in line 24 from the above screenshot records an entry in the JSON log file. Examining the JSON file, we can see this entry here:
{ "@t": "2023-09-13T17:43:29.9853185Z", "@m": "Entered GetWeatherForecast", "@i": "7806fd59", "SourceContext": "AudioNotes.Web.Controllers.WeatherForecastController", "ActionId": "f641ffdf-2698-4c99-bb8c-c35fb2836e5f", "ActionName": "AudioNotes.Web.Controllers.WeatherForecastController.Get (AudioNotes.API)", "RequestId": "0HMTKCV3SKO43:00000009", "RequestPath": "/WeatherForecast", "ConnectionId": "0HMTKCV3SKO43" }
The logging information we recorded is stored in the property @m.
~
AppSettings.JSON
Finally, the amount of logging you want to store can be defined by setting the relevant value in the appsettings.json file for the project.
Look for this section and set it to the relevant value:
"Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }
Learn more about the different log levels, what they can be set to, and the typical use cases here.
~
Summary
In this blog post, you’ve learned how to perform file logging using .NET Core 6 and the Serilog.Extensions.Logging.File NuGet package.
Use this if you need to augment existing out of the box capabilities with .NET Core logging or if you don’t have access to log data in Application Insights in Azure.
~
Further Reading and Resources
The following resources will give you more information about logging and dependency injection in .NET:
Leave a Reply