SerilogSinksInMemory
SerilogSinksInMemory copied to clipboard
Use from a controller?
Hi,
I try to use from a controller but InMemorySink.Instance.LogEvents seems always empty, does I need to configure any DI?
Regards
Would you be able to share a code sample of how you’re attempting to do this?
Hi, yes sure, this is my service:
public class LogService(InMemorySink memorySink)
{
public IEnumerable<Log> GetAll() => memorySink.LogEvents
.DistinctBy(logEvent => logEvent.MessageTemplate.Text)
.Select(logEvent => new Log
{
Date = logEvent.Timestamp,
Level = logEvent.Level switch
{
LogEventLevel.Information => SeverityLevels.Information,
LogEventLevel.Warning => SeverityLevels.Warning,
LogEventLevel.Error or LogEventLevel.Fatal => SeverityLevels.Error,
_ => SeverityLevels.Trace
},
Message = logEvent.RenderMessage()
});
}
Do you need more stuffs @sandermvanvliet?
Without seeing a repro case it's a bit difficult for me to determine where this may be breaking down.
I see you're passing in a InMemorySink instance but I don't know how you've configured Serilog and are consuming that Serilog ILogger instance elsewhere.
One thing that could happen is that the logger is disposed before you're calling GetAll() from your LogService. I've seen before that all log entries are gone then.
I will try to give you more part of the code, and before check what you said
Hey @sandermvanvliet
I understood the issue, all logs was in double, but I guess its because I had WriteTo.InMemory() and also in-memory in appsettings.json, when I comment it like below all works fine!
Log.Logger = new LoggerConfiguration()
// .WriteTo.InMemory()
.ReadFrom.Configuration(builder.Configuration)
.CreateLogger();
Mixing and matching file and code configuration is a recipe for disaster so I’m not entirely surprised this happened 😅
Yeah, didn't really knew how this lib was working, and didn't really pay attention :)