Logging

Posted on August 21st, 2022

Part of Notes on .NET

Talks aboutC#.NET

Logging comes out of the box with ASP using ILogger<> from the Microsoft.Extensions.Logging package.

The generic parameter specifies a category (the source of the log). It's arbitrary but the enclosing class is the convention. The log level (how bad/important it is) is specified with the LogLevel enum or dedicated methods.

public class SomeService
{
  public SomeService(ILogger<IndexModel> logger) {...}
  public void SomeMethod()
  {
    logger.LogInformation("something");
    logger.Log(LogLevel.Error, "something else");
  }
}

We can specify the minimum severity of logs per-assembly using filters.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    }
  }
}

Performance

Logging can introduce performance issues in many applications. Unless a directly-loggable value is provided (basically primitives), the logger needs to do some conversion/serialisation. Combine that with the fact that console logging is synchronous and the overhead can be comparatively huge.

By defining a delegate with the LoggerMessage class, we can create a cache-able delegates with strong types, requiring fewer allocations and eliminating boxing to reduce computational overhead.

// No parameters
LoggerMessage.Define(
  LogLevel.Information,
  0, // ID
  "Gonna do something"
);

// One parameter of int
withParam = LoggerMessage.Define<int>(
  LogLevel.Warning,
  1,
  "User not found: {Id}"
);

// Scoped
LoggerMessage.DefineScope<int>("Scope with an int: {i}");
LoggerMessage examples.

Custom Exception Handling

In the backend, custom exception handling is implemented via a filter deriving from .NET also offers an inbuilt exception page for ExceptionFilterAttribute developers, added with app.UseDeveloperExceptionPage().

In the frontend, app.UseExceptionHandler("/Error") specifies a Razor page to display errors & exceptions to the user.

UseExceptionHandler middleware allows exceptions throughout the application to be captured, and automates page redirects.

Destinations

Also referred to as providers, sinks, or targets.

Files are the easiest choice but not the best:

Cloud-hosting services offer solutions, such as Azure's Application Insights or App Service Diagnostics, integrated into ASP with Microsoft.Extensions.Logging.AzureAppServices.

Packages like Serilog can connect to many external services to store logs.