Created
June 27, 2021 22:08
-
-
Save frekw/9f810628b1f5ed860ee9fbae86ee60a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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