Skip to content

Instantly share code, notes, and snippets.

@frekw
Created June 27, 2021 22:08
Show Gist options
  • Save frekw/9f810628b1f5ed860ee9fbae86ee60a4 to your computer and use it in GitHub Desktop.
Save frekw/9f810628b1f5ed860ee9fbae86ee60a4 to your computer and use it in GitHub Desktop.
def accessLogger[R, E](
next: Http[R, E, Request, HttpResponse[R, E]]
): HttpApp[R with clock.Clock with Logging, E] = {
Http.flatten {
Http.fromEffectFunction[Request] { req =>
val path = req.url.path
val method = req.method
clock.instant.flatMap(start => {
val logSuccess = (resp: HttpResponse[R, E]) => {
Http.fromEffect(zio.clock.instant.flatMap(end => {
val duration = end.toEpochMilli - start.toEpochMilli
Logging
.locally(LogAnnotation.Name("access-log" :: Nil)) {
Logging.info(
s"path: $path, method: $method, status: ${resp.status},timeMillis: $duration"
)
}
})) *> Http.succeed(resp)
}
val logError = (err: E) => {
Http.fromEffect(clock.instant.flatMap(end => {
val duration = end.toEpochMilli - start.toEpochMilli
Logging
.locally(LogAnnotation.Name("access-log" :: Nil)) {
Logging.info(
s"path: $path, method: $method, failed: ${err},timeMillis: $duration"
)
}
})) *> Http.fail(err)
}
val logNotFound = Http.fromEffect {
clock.instant.flatMap(end => {
val duration = end.toEpochMilli - start.toEpochMilli
Logging
.locally(LogAnnotation.Name("access-log" :: Nil)) {
Logging.info(
s"path: $path, method: $method, not found,timeMillis: $duration"
)
}
})
} *> Http.empty
ZIO.succeed(
next.foldM(
e => logError(e),
v => logSuccess(v),
logNotFound
)
)
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment