Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 987
rabejens Avatar asked Apr 24 '19 14:04

rabejens


People also ask

How do you pass data on Blazor?

By using Blazor route parameters, you can pass values from one page to another page. Use NavigationManager to pass a value and route the parameter to another page. Follow this example to achieve passing values from one page to another.

Does hot reload work with Blazor?

Blazor WebAssemblyHot Reload reacts to most changes to method bodies, such as adding, removing, and editing variables, expressions, and statements. Changes to the bodies of lambda expressions and local functions are also supported.


1 Answers

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.

like image 103
poke Avatar answered Sep 25 '22 00:09

poke