How can I write into the browser´s console via Blazor WebAssembly?

I usually do something like this:

Console.WriteLine("My debug output.");

if it's Blazor WebAssembly, I see the message in the browser´s console.

If it's Blazor Server App I see the message in the Output window. (In the output window, there is a dropdown - select: " ASP.NET Core Web Server")

Hope this helps...


You can user an ILogger<T> that give you the possibility to write warning or error in the console :

@using Microsoft.Extensions.Logging
@inject ILogger<MyComponent> _logger
...
@code {

     protected override void OnInitialized()
     {
          _logger.LogWarning("warning");
          _logger.LogError("error");
     }
}


If your using Blazor Server (not WebAssembly) you can only write to the browser console using JSInterop. I wrote a wrapper class like this:

public class JsConsole
{
   private readonly IJSRuntime JsRuntime;
   public JsConsole(IJSRuntime jSRuntime)
   {
       this.JsRuntime = jSRuntime;
   }

   public async Task LogAsync(string message)
   {
       await this.JsRuntime.InvokeVoidAsync("console.log", message);
   }
}

Then in your page, you can inject the JsConsole and use it:

await this.JsConsole.Log(message); //Will show in the browser console.