-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
WebAssemblyConsoleLogger.cs
167 lines (146 loc) · 6.02 KB
/
WebAssemblyConsoleLogger.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Text;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using Microsoft.JSInterop.WebAssembly;
namespace Microsoft.AspNetCore.Components.WebAssembly.Services;
internal class WebAssemblyConsoleLogger<T> : ILogger<T>, ILogger
{
private const string _loglevelPadding = ": ";
private static readonly string _messagePadding = new(' ', GetLogLevelString(LogLevel.Information).Length + _loglevelPadding.Length);
private static readonly string _newLineWithMessagePadding = Environment.NewLine + _messagePadding;
private static readonly StringBuilder _logBuilder = new StringBuilder();
private readonly string _name;
private readonly WebAssemblyJSRuntime _jsRuntime;
public WebAssemblyConsoleLogger(IJSRuntime jsRuntime)
: this(string.Empty, (WebAssemblyJSRuntime)jsRuntime) // Cast for DI
{
}
public WebAssemblyConsoleLogger(string name, WebAssemblyJSRuntime jsRuntime)
{
_name = name ?? throw new ArgumentNullException(nameof(name));
_jsRuntime = jsRuntime ?? throw new ArgumentNullException(nameof(jsRuntime));
}
public IDisposable? BeginScope<TState>(TState state) where TState : notnull
{
return NoOpDisposable.Instance;
}
public bool IsEnabled(LogLevel logLevel)
{
return logLevel != LogLevel.None;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
if (formatter == null)
{
throw new ArgumentNullException(nameof(formatter));
}
var message = formatter(state, exception);
if (!string.IsNullOrEmpty(message) || exception != null)
{
WriteMessage(logLevel, _name, eventId.Id, message, exception);
}
}
private void WriteMessage(LogLevel logLevel, string logName, int eventId, string message, Exception? exception)
{
lock (_logBuilder)
{
try
{
CreateDefaultLogMessage(_logBuilder, logLevel, logName, eventId, message, exception);
var formattedMessage = _logBuilder.ToString();
switch (logLevel)
{
case LogLevel.Trace:
case LogLevel.Debug:
// Although https://console.spec.whatwg.org/#loglevel-severity claims that
// "console.debug" and "console.log" are synonyms, that doesn't match the
// behavior of browsers in the real world. Chromium only displays "debug"
// messages if you enable "Verbose" in the filter dropdown (which is off
// by default). As such "console.debug" is the best choice for messages
// with a lower severity level than "Information".
_jsRuntime.InvokeVoid("console.debug", formattedMessage);
break;
case LogLevel.Information:
_jsRuntime.InvokeVoid("console.info", formattedMessage);
break;
case LogLevel.Warning:
_jsRuntime.InvokeVoid("console.warn", formattedMessage);
break;
case LogLevel.Error:
_jsRuntime.InvokeVoid("console.error", formattedMessage);
break;
case LogLevel.Critical:
_jsRuntime.InvokeUnmarshalled<string, object>("Blazor._internal.dotNetCriticalError", formattedMessage);
break;
default: // invalid enum values
Debug.Assert(logLevel != LogLevel.None, "This method is never called with LogLevel.None.");
_jsRuntime.InvokeVoid("console.log", formattedMessage);
break;
}
}
finally
{
_logBuilder.Clear();
}
}
}
private static void CreateDefaultLogMessage(StringBuilder logBuilder, LogLevel logLevel, string logName, int eventId, string message, Exception? exception)
{
logBuilder.Append(GetLogLevelString(logLevel));
logBuilder.Append(_loglevelPadding);
logBuilder.Append(logName);
logBuilder.Append('[');
logBuilder.Append(eventId);
logBuilder.Append(']');
if (!string.IsNullOrEmpty(message))
{
// message
logBuilder.AppendLine();
logBuilder.Append(_messagePadding);
var len = logBuilder.Length;
logBuilder.Append(message);
logBuilder.Replace(Environment.NewLine, _newLineWithMessagePadding, len, message.Length);
}
// Example:
// System.InvalidOperationException
// at Namespace.Class.Function() in File:line X
if (exception != null)
{
// exception message
logBuilder.AppendLine();
logBuilder.Append(exception.ToString());
}
}
private static string GetLogLevelString(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Trace:
return "trce";
case LogLevel.Debug:
return "dbug";
case LogLevel.Information:
return "info";
case LogLevel.Warning:
return "warn";
case LogLevel.Error:
return "fail";
case LogLevel.Critical:
return "crit";
default:
throw new ArgumentOutOfRangeException(nameof(logLevel));
}
}
private class NoOpDisposable : IDisposable
{
public static NoOpDisposable Instance = new NoOpDisposable();
public void Dispose() { }
}
}