DEV Community

Cover image for Write to the console.log with styles from Blazor
Emanuele Bartolesi
Emanuele Bartolesi

Posted on

7

Write to the console.log with styles from Blazor

The console is a very good companion for every web developer.
We use the console to log everything and for various reasons.
In this post I will show how to add some CSS styles to the console application just for having fun or for adding value to the logs in the developer tools console of the browser.

To add CSS styles to the console, we use the format specifier %c at the beginning of the string.
And as a second parameter we can add some CSS rules.
Take a look to the script below:



console.log("%cThis is a red text", "red");


Enter fullscreen mode Exit fullscreen mode

Easy.
But how we can use the same features, but from a Blazor application?
It's easy as well.

Open the razor page where you want to add the console formatting and insert the injection for JSRuntime.
Then in the InitializedAsync or on a click event, call the console.log method from Blazor.
You can use the same parameters that you are using from JavaScript.
Below you can find the entire code to add to your application.



@code {
    @inject IJSRuntime JSRuntime

    protected override async Task OnInitializedAsync()
    {
        await JSRuntime.InvokeVoidAsync("console.log", "%cRed Origin  5.0.1 ๐Ÿš€", "color:#0dd8d8; background:#0b1021; font-size:1.5rem; padding:0.15rem 0.25rem; margin: 1rem auto; font-family: Rockwell; border: 2px solid #0dd8d8; border-radius: 4px;font-weight: bold; text-shadow: 1px 1px 1px #00af87bf;");
    }
}


Enter fullscreen mode Exit fullscreen mode

In this case, in the console you can find a message like in this picture:


Thanks for reading this post, I hope you found it interesting!

Feel free to follow me to get notified when new articles are out ๐Ÿ™‚

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay