Skip to content

Logging

Arsenty Politov edited this page Mar 15, 2019 · 1 revision

Logging extensions and providers

Provides:

  • HttpErrorLoggingMiddleware that intercepts failed http requests and logs them.
  • RepositoryLoggerProvider that can be used to log events to the repository.

Related packages

  • DevGuild.AspNetCore.Services.Logging
  • DevGuild.AspNetCore.Services.Logging.Data

HttpErrorLoggingMiddleware

A middleware that intercepts failed requests and logs the exception for further investigation.

HttpErrorLoggingMiddleware Usage

To use this middleware, add the following line to Configure method of Startup class after adding other exception handlers:

app.UseHttpErrorLogging();

You can customize logger category by passing it as a parameter of UseHttpErrorLogging extension:

app.UseHttpErrorLogging("Custom.Category");

Unhandled exception will be logged at Warning level.

RepositoryLoggerProvider

A logging provider that records events in the database.

Stored information

  • Request information:
    • Service host
    • Method: GET, POST, etc
    • Request URI - both path and query
    • User ip address
    • User agent
    • User name - name of the authenticated user if any
    • Unique request id - can be used to trace multiple events to a single request
  • Event information:
    • Timestamp
    • Log level - Critical, Error, Warning, Information, Debug or Trace
    • Category
    • Event ID
    • Event name
    • Scope
    • Message
  • Exception information:
    • Exception class
    • Exception message
    • Exception details

Request information is only available when logging events that happen during request processing. In other cases, this information can be set via IRequestInformationProvider service:

public void Example1(IRequestInformationProvider requestInformationProvider)
{
    requestInformationProvider.OverrideRequestInformation(new RequestInformation(
        requestHost: "",
        requestMethod: "",
        requestAddress: "",
        userAddress: "",
        userAgent: "",
        userName: "",
        requestId: ""));
}

Stored information Usage

RepositoryLoggerProvider requires IRequestInformationProvider to be available as a singleton. Add following line to ConfigureServices method of Startup class:

services.AddSingleton<IRequestInformationProvider, RequestInformationProvider>();

After that, add the following call during web host creation in Program class:

.ConfigureLogging(logging => logging.AddRepositoryLogging())

Example of resulting CreateWebHostBuilder method:

public static IWebHostBuilder CreateWebHostBuilder(String[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging(logging => logging.AddRepositoryLogging())
        .UseStartup<Startup>();
Clone this wiki locally