您可以创建自定义记录器。我设法让它与这个 tutorial chat-app
一起工作
Startup.cs
loggerFactory.AddProvider(
new SignalRLoggerProvider(
new SignalRLoggerConfiguration
{
HubContext = serviceProvider.GetService<IHubContext<BlazorChatSampleHub>>(),
LogLevel = LogLevel.Information
}));
public class SignalRLoggerProvider : ILoggerProvider
{
private readonly SignalRLoggerConfiguration _config;
private readonly ConcurrentDictionary<string, SignalRLogger> _loggers = new ConcurrentDictionary<string, SignalRLogger>();
public SignalRLoggerProvider(SignalRLoggerConfiguration config)
{
_config = config;
}
public ILogger CreateLogger(string categoryName)
{
return _loggers.GetOrAdd(categoryName, name => new SignalRLogger(name, _config));
}
public void Dispose()
{
_loggers.Clear();
}
}
public class SignalRLogger : ILogger
{
private readonly string _name;
private readonly SignalRLoggerConfiguration _config;
public SignalRLogger(string name, SignalRLoggerConfiguration config)
{
_name = name;
_config = config;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return logLevel == _config.LogLevel;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
if (_config.EventId == 0 || _config.EventId == eventId.Id)
{
this._config.HubContext?.Clients.Group(_config.GroupName).SendAsync("Broadcast", "LOGGER", $"{DateTimeOffset.UtcNow:T}-UTC : {formatter(state, exception)}");
}
}
}
Proof of concept