Skip to content

Handling of Serilog.Events.LogEvent in LokiBatchFormatter is not thread-safe #224

@k-wojcik

Description

@k-wojcik

Which version of Serilog.Sinks.Grafana.Loki are you using?

v8.2.0

Which version of .NET are you using?

net6.0

Describe the bug

Handling of Serilog.Events.LogEvent in LokiBatchFormatter is not thread-safe.
Method AddLevelAsPropertySafely modifies Serilog.Events.LogEvent.Properties (Dictionary<string, LogEventPropertyValue>) and causes problems with simultaneous aceess to it from other threads (sinks).

https://github.com/serilog-contrib/serilog-sinks-grafana-loki/blob/master/src/Serilog.Sinks.Grafana.Loki/LokiBatchFormatter.cs#L157-L158

image

serilog/serilog#1154 (comment)
Serilog's LogEvent is not thread-safe for readers concurrent with writers; concurrent reads are fine, but only in the absence of writes

To Reproduce

Configure at least one sink with async processing alongside Serilog.Sinks.Grafana.Loki, for example I use sinks:

  • Serilog.Sinks.Async + Serilog.Sinks.File,
  • Serilog.Sinks.Seq

Expected behavior

The original value of Serilog.Events.LogEvent.Properties should never be modified in sink.

Log/SelfLog output or exception with stacktrace

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
   at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()
   at Serilog.Formatting.Compact.CompactJsonFormatter.FormatEvent(LogEvent logEvent, TextWriter output, JsonValueFormatter valueFormatter)
   at Serilog.Sinks.Seq.ConstrainedBufferedFormatter.Format(LogEvent logEvent, TextWriter output, Boolean writePlaceholders)

Application or code sample, which could be used to reproduce a bug

No response

Additional context

No response

I have read the documentation

Metadata

Metadata

Assignees

Labels

bugSomething isn't workinggood first issueGood for newcomers

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions