outr / scribe

The fastest logging library in the world. Built from scratch in Scala and programmatically configurable.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is it safe to use MDC with cats-effect?

rolman243 opened this issue · comments

I use scribe with cats-effect-3. I want to add at least a trace id to all my logs and I was thinking about using MDC for this.

Is it safe to use MDC in combination with ce3 as the MDC state has to be saved and restored when execution switches between threads?

In Scribe, MDC works differently than other libraries. If you make all of your methods receive an implicit MDC then you can propagate the MDC state across multiple threads easily and it works very well with cats-effect. In the Spice web server there's a good example of this: https://github.com/outr/spice/blob/master/server/src/main/scala/spice/http/server/handler/HttpHandler.scala#L12

Thanks for your reply. I want to avoid using an implicit parameter because I'm developing a library which will be used for multiple business applications. Adding an extra implicit parameter in the library will put a technical implementation detail into the business logic of all applications which will use the lib. I'll keep the implicit parameter solution in mind and try to find another solution.

Do you have another idea in mind? I'm happy to expand the functionality of MDC if there's another route that would be better?

If typelevel/cats-effect#3636 gets merged I believe we can have a MDCManager that's backed by a mdc: IOLocal[MDC] and we leverage cats.effect.unsafe.IOLocals.get and cats.effect.unsafe.IOLocals.set to implement both of the following methods.

trait MDCManager {
  def instance: MDC
  def instance_=(mdc: MDC): Unit
}

(only works with -Dcats.effect.ioLocalPropagation=true)

Very cool! Looking forward to that getting merged.