(20/30) Everyone learns Blazor together: Logging

(20/30) Everyone learns Blazor together: Logging

When developing a system, recording is a very important thing. It has not been mentioned before. I only thought of this recently, so let's implement it!

最后更新 12/21/2021 11:36 PM
StrayaWorker
预计阅读 3 分钟
分类
Blazor
专题
Learn the Blazor series together
标签
.NET C# ASP.NET Core Blazor

When developing a system, recording is a very important thing. It has not been mentioned before. I only thought of this recently, so let's implement it!

由于笔者用的是Blazor Server,官方文件提供的只有Blazor WebAssembly 的做法,所以先来试试看后者。

首先打开之前建立的BlazorWasm 项目,在Counter.razor加入@using Microsoft.Extensions.Logging;及注入服务@inject ILogger<Counter> _logger;,接着在原本的IncrementCount()内加入要提示的信息,这边用的是LogWarning(),除此之外还有LogCriticalLogDebugLogError等等可以使用。

@page "/counter" @using Microsoft.Extensions.Logging @inject ILogger<Counter>
  _logger

  <PageTitle>Counter</PageTitle>

  <h1>Counter</h1>

  <p role="status">Current count: @_currentCount</p>

  <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

  @code { private int _currentCount; private void IncrementCount() {
  _logger.LogWarning("有美女点击我了!"); _currentCount++; } }</Counter
>

接着将启动项目改成BlazorWasm 项目,启动后前往Counter 页面,点击按钮后,按下F12 切换到Console 页签,可以看到显示了我们定义的信息。

Blazor WebAssembly 这么简单,那在Blazor Server 也是一样吗?

可惜的是Blazor Server 并不支持这样的做法,目前只能用IJSRuntime的方式调用浏览器的console.log提示信息,想要有不同层级的信息也必须自己定制化。

我们切回Blazor Server 项目,在JsInteropClasses加入ConsoleLog()方法,里面做的事情就只有调用console.log()

public async Task ConsoleLog(string message)
{
	await _js.InvokeAsync<object?>("console.log", message);
}

接着在Blog.razor.cs覆写OnAfterRenderAsync(),在里面调用ConsoleLog()

protected override async Task OnAfterRenderAsync(bool firstRender)
{
	await _jsClass!.ConsoleLog("这是Blazor Server的console.log信息");
}

之所以不写在OnInitializedAsync()是因为我们采用预先渲染(pre-render)的方式,此时的JavaScript 还没准备好,如果在OnInitializedAsync()调用,会发生下图的错误。

要是一定要在OnInitializedAsync()调用的话,可以去_Layout.cshtml<component>render-mode属性从ServerPrerendered改为Server

Server 的render-mode分为三种:StaticServerServerPrerendered,第一种速度最快,将全部Component都转变为静态 HTML 文件;第二种最慢,会先将一种标记传出,等到使用者启动该Component 后才会真的渲染成HTML 文件;第三种是折衷方案,先把Component 变成静态HTML 文件但没有交互功能,等到使用者启动该Component 后才会通知Server 将功能补上。

这也是为什么render-mode改成Server才有效的原因,因为此时的ConsoleLog()还没转成 JavaScript 文件。

** Quotes: **

  1. ASP.NET Core Blazor logging
  2. LoggerExtensions Class
  3. How can I write into the browser´s console via Blazor WebAssembly?
  4. Blazor Server
  5. What's the difference between RenderMode.Server and RenderMode.ServerPrerendered in blazor?
  6. RenderMode Enum

** Note: The code in this article is refactored through. NET 6 + Visual Studio 2022. You can click on the original link to compare and learn the refactored code. Thank you for reading and support the original author **

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 12/25/2021

(29/30) Everyone learn Blazor together: Blazor unit testing

Probably the most boring process of developing a system is to solve bugs, especially the error of trying to value null objects (`Object reference not set to an instance of an object.`). This should be the most common problem that most people encounter when they first step into the programming field. In order to relieve themselves from the boring process of solving bugs, this article introduces 'unit testing'.

继续阅读
同分类 / 同标签 12/25/2021

(28/30) Everyone learns Blazor together: Policy-based authorization

It was mentioned before that 'ASP.NET Core Identity' uses 'Claim' based authentication. In fact,'ASP.NET Core Identity' has different types of authorization methods, the simplest are 'login authorization','role authorization', and 'Claim authorization', but all of the above are implemented in one way: 'Policy-based authorization'.

继续阅读