简体   繁体   中英

How to add logging to Blazor Server-side component?

I am trying to create a hosted ASP.net Blazor application and trying to get a logger into my controller.

I have this:

public MyController(ILogger logger) {
    _logger = logger;
    // more initialization
}

But when I run it, I get:

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'MyApp.Server.Controllers.MyController'.

As there are a lot of log messages scrolling by, I guess Blazor already initializes a logger.

How do I access this?

The non-generic ILogger is not registered with the service collection. Instead, you are supposed to inject a generic ILogger<T> . The generic type argument T is used to set up the category name that is linked with the logger instance. It allows you to easily see where a log call came from.

Usually, you specify the type that you are using the logger with as the generic type argument. So in your case, you would use ILogger<MyController> :

public MyController(ILogger<MyController> logger)
{
    _logger = logger;
}

Note that there is nothing special to server-side Blazor about this behavior. This is standard ASP.NET Core and the controller is also a normal ASP.NET Core controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM