is there a way to stream blazor logs to the client and display them in real time on a web page?

You could create a custom logger. I managed to get this to work with this 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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top