
30/10/2024
Logging is a crucial aspect of application development, allowing developers to monitor the application’s behavior, capture errors, and provide insights into usage patterns. .NET Core provides a robust logging framework that is both flexible and easy to use. Let’s dive into how to implement logging in .NET Core applications step-by-step.
.NET Core comes with a built-in logging framework that supports various logging providers. The primary logging interfaces are found in the Microsoft.Extensions.Logging namespace, which is included by default in most .NET Core applications.
ILogger.Starting with a new .NET Core Web application template is straightforward. Open your command line and use the following command:
dotnet new webapp -n MyLoggingApp cd MyLoggingApp
In a web application, logging is typically configured in the Startup.cs file. The ConfigureServices method sets up the logging services, and the Configure method can be used to define how you want logging output.
Here's how you can configure it:
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddLogging(config => { config.AddDebug(); config.AddConsole(); }); services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); logger.LogInformation("Development mode active."); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); logger.LogWarning("Production mode active."); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } }
Now, let’s see how we can log messages throughout the application. You can inject ILogger<T> into your controllers or other classes.
Here’s an example controller:
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { _logger.LogInformation("Index page accessed."); return View(); } public IActionResult Privacy() { _logger.LogWarning("Privacy page accessed."); return View(); } }
In this example, we log an informational message when the Index page is accessed and a warning when the Privacy page is accessed.
By default, logging levels can be filtered via the appsettings.json file. For example, you can specify minimum log levels for different namespaces.
Here’s how you can set that up:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, }
The built-in logger is great, but sometimes you may want to use third-party logging frameworks like Serilog or NLog.
To add Serilog, first, install the necessary packages:
dotnet add package Serilog.AspNetCore dotnet add package Serilog.Sinks.Console
Next, configure Serilog in Program.cs:
using Serilog; public class Program { public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); try { Log.Information("Starting up the web host"); CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { Log.Fatal(ex, "Application start-up failed"); } finally { Log.CloseAndFlush(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseSerilog() .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }
Now, you can leverage the rich features of Serilog, such as structured logging and sending logs to various external sources.
For production applications, Microsoft Azure Application Insights is an excellent choice for logging and telemetry.
To implement it:
Install the required NuGet package:
dotnet add package Microsoft.ApplicationInsights.AspNetCore
Configure Application Insights in Startup.cs:
public void ConfigureServices(IServiceCollection services) { services.AddApplicationInsightsTelemetry(Configuration["ApplicationInsights:InstrumentationKey"]); // Other service configurations... }
Make sure to set your Instrumentation Key in your configurations to connect to Azure Application Insights.
Logging in .NET Core is versatile and powerful, allowing you to monitor and troubleshoot your applications effectively. Experiment with built-in logging and explore third-party providers like Serilog and Application Insights to enhance your logging strategies further.
30/10/2024 | DotNet
30/10/2024 | DotNet
30/10/2024 | DotNet
30/10/2024 | DotNet
30/10/2024 | DotNet