0

I have a .NET 8 Blazor WASM web application. I am trying to implement Serilog to push logs back to my API Server application.

I saw this thread: Use serilog as logging provider in blazor webassembly client app

But it uses Serilog.Sinks.BrowserHttp which no longer works.

The problem is with the WebAssemblyHttpMessageHander. Which looks like a proper fix was released and confirmed by @Jernejk the OP. However, I can't find a working example of how they fixed it. They moved aware from WebAssemblyHttpMessageHander and are using HttpClient, but I can't figure out how to generate the proper HttpClient in this case.

Does anyone have a working example of how to use Serilog in Blazor WASM to write logs back to a file on the server?

1 Answer 1

0

You could try implement Custom Sink to send logs via httpclient

    public class BrowserHttpSink : ILogEventSink
    {
        private readonly HttpClient _httpClient;
        private readonly string _url;

        public BrowserHttpSink(HttpClient httpClient, string url)
        {
            _httpClient = httpClient;
            _url = url;
        }

        public void Emit(LogEvent logEvent)
        {
            var logMessage = logEvent.RenderMessage();
            var logData = new { Message = logMessage, Level = logEvent.Level.ToString() };

            var jsonContent = new StringContent(JsonSerializer.Serialize(logData), System.Text.Encoding.UTF8, "application/json");
            _httpClient.PostAsync(_url, jsonContent);
        }
    }

program.cs

var httpClient = new HttpClient();
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console() // Optionally log to the console
    .WriteTo.Sink(new BrowserHttpSink(httpClient, "http://localhost:5140/LogAPI"))
    .CreateLogger();

builder.Logging.AddSerilog(Log.Logger);

The controller

        public class MyLog
        {
            public string Message { get; set; }
            public string Level { get; set; }
        }
        [HttpPost("logapi")]
        public void logapi(MyLog myLog)
        {
         //manually write to file.
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.