correlator
correlator copied to clipboard
Correlation id support
See the blog for introduction.
Currently supports monix & logback.
Generic usage:
- add the dependency:
"com.softwaremill.correlator" %% "monix-logback-http4s" % "0.1.9"to your project - create an object extending the
CorrelationIdDecoratorclass, e.g.object MyCorrelationId extends CorrelationIdDecorator() - call
MyCorrelationId.init()immediately after your program starts (in themain()method) - create an implicit instance of
CorrelationIdSourcefor givenTfrom which you want to extract correlation id - wrap any
T => Task[R]function withMyCorrelationId.withCorrelationId, so that a correlation id is extracted from the argument (using the definedCorrelationIdSource), or a new one is created. - you can access the current correlation id (if any is set) using
MyCorrelationId.apply()orMyCorrelationId.applySync().
For http4s integration:
- add the dependency:
"com.softwaremill.correlator" %% "monix-logback-http4s" % "0.1.9"to your project - create an object extending the
CorrelationIdDecoratorclass, e.g.object MyCorrelationId extends CorrelationIdDecorator() - call
MyCorrelationId.init()immediately after your program starts (in themain()method) - wrap your
HttpRoutes[Task]withHttp4sCorrelationMiddleware(MyCorrelationId).withCorrelationId, so that a correlation id is extracted from the request (using the provided header name), or a new one is created. - you can access the current correlation id (if any is set) using
MyCorrelationId.apply()orMyCorrelationId.applySync().
Logging each request with corresponding correlationId can be done in following way:
def loggingMiddleware[T, R](
service: HttpRoutes[Task],
logStartRequest: Request[Task] => Task[Unit] = req =>
Task(MyLogger.debug(s"Starting request to: ${req.uri.path}"))
): HttpRoutes[Task] = Kleisli{ req: Request[Task] =>
val setupAndService = for {
_ <- logStartRequest(req)
r <- service(req).value
} yield r
OptionT(setupAndService)
}
val middleware = Http4sCorrelationMiddleware(correlationIdDecorator)
middleware.withCorrelationId(loggingMiddleware(service))