Skip to content

Commit

Permalink
Log failed requests by default
Browse files Browse the repository at this point in the history
  • Loading branch information
lenguyenthanh committed Dec 12, 2023
1 parent d3259b0 commit fce24ec
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
22 changes: 22 additions & 0 deletions app/src/main/scala/http/ApiLogger.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package lila.fishnet
package http

import cats.data.Kleisli
import cats.syntax.all.*
import cats.effect.IO
import org.http4s.internal.Logger as Http4sLogger
import org.http4s.{ HttpApp, Response }
import org.typelevel.log4cats.Logger

object ApiErrorLogger:

def logOnError: Response[IO] => Boolean = res => !res.status.isSuccess && res.status.code != 404
def instance(using Logger[IO]): HttpApp[IO] => HttpApp[IO] = http =>
Kleisli: req =>
http(req).flatTap: res =>
logOnError(res)
.pure[IO]
.ifM(
Http4sLogger.logMessage[IO](res)(logHeaders = true, logBody = true)(Logger[IO].warn),
IO.unit
)
21 changes: 14 additions & 7 deletions app/src/main/scala/http/HttpApi.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ import cats.effect.IO
import org.http4s.*
import org.http4s.implicits.*
import org.http4s.server.middleware.*
import org.typelevel.log4cats.Logger

final class HttpApi(executor: Executor, healthCheck: HealthCheck, config: HttpServerConfig):
final class HttpApi(
executor: Executor,
healthCheck: HealthCheck,
config: HttpServerConfig
)(using Logger[IO]):

private val fishnetRoutes = FishnetRoutes(executor).routes
private val healthRoutes = HealthRoutes(healthCheck).routes
Expand All @@ -23,11 +28,13 @@ final class HttpApi(executor: Executor, healthCheck: HealthCheck, config: HttpSe

private val middleware = autoSlash andThen timeout

private val loggers: HttpApp[IO] => HttpApp[IO] =
RequestLogger.httpApp[IO](false, true) andThen
ResponseLogger.httpApp[IO, Request[IO]](false, true)
private def verboseLogger =
RequestLogger.httpApp[IO](true, true) andThen
ResponseLogger.httpApp[IO, Request[IO]](true, true)

private val loggers =
if config.apiLogger then verboseLogger
else ApiErrorLogger.instance

val httpApp: HttpApp[IO] =
val app = middleware(routes).orNotFound
if config.apiLogger then loggers(app)
else app
loggers(middleware(routes).orNotFound)

0 comments on commit fce24ec

Please sign in to comment.