14

In JavaScript we can use the following call to write debug output to the browser´s console:

console.log("My debug output.");

Output in Google Chrome:

console output in google chrome

How can I log "My debug output" in my component to the browser´s console via Blazor WebAssembly?

<button @onclick="ClickEvent">OK</button>

@code {

    private void ClickEvent()
    {
        // console.log("My debug output.");
    }
}
Simon
  • 3,043
  • 1
  • 35
  • 66
  • 1
    I think you can do it in c# using `Console.WriteLine("My debug output.");` with capital c – Alexan Apr 02 '20 at 13:26

4 Answers4

23

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...

Greg Gum
  • 25,941
  • 27
  • 127
  • 194
enet
  • 26,272
  • 2
  • 38
  • 70
10

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.
Greg Gum
  • 25,941
  • 27
  • 127
  • 194
9

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");
     }
}

alvarez
  • 658
  • 7
  • 17
agua from mars
  • 12,886
  • 4
  • 47
  • 56
  • ILogger: [By default, Blazor apps log to console output with the Console Logging Provider. ... During development, Blazor usually sends the full details of exceptions to the browser's console to aid in debugging. In production, detailed errors in the browser's console are disabled by default](https://docs.microsoft.com/en-us/aspnet/core/blazor/handle-errors?view=aspnetcore-3.1#log-errors-with-a-persistent-provider) – dani herrera Apr 02 '20 at 14:25
-1

Just crate a variable and change it if ur things work.. for example

<p>@message</p>
<button onclck=@Send></button>
@code {
   private string message = "Don`t work";

   public void Send()
{
  message = "working"
}
}

I hope it helps...