SerilogSinksInMemory icon indicating copy to clipboard operation
SerilogSinksInMemory copied to clipboard

Use from a controller?

Open imclint21 opened this issue 1 year ago • 5 comments

Hi,

I try to use from a controller but InMemorySink.Instance.LogEvents seems always empty, does I need to configure any DI?

Regards

imclint21 avatar Jun 02 '24 13:06 imclint21

Would you be able to share a code sample of how you’re attempting to do this?

sandermvanvliet avatar Jun 27 '24 18:06 sandermvanvliet

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()
		});
}

imclint21 avatar Aug 02 '24 20:08 imclint21

Do you need more stuffs @sandermvanvliet?

imclint21 avatar Aug 03 '24 16:08 imclint21

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.

sandermvanvliet avatar Aug 06 '24 17:08 sandermvanvliet

I will try to give you more part of the code, and before check what you said

imclint21 avatar Aug 06 '24 22:08 imclint21

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();

imclint21 avatar Jan 10 '25 13:01 imclint21

Mixing and matching file and code configuration is a recipe for disaster so I’m not entirely surprised this happened 😅

sandermvanvliet avatar Jan 11 '25 19:01 sandermvanvliet

Yeah, didn't really knew how this lib was working, and didn't really pay attention :)

imclint21 avatar Jan 11 '25 19:01 imclint21