How to Log HTTP Requests and Add Log Annotations
In this guide, we add logging to a ZIO HTTP server without touching its handlers. By the end, the server writes one log line for every request it serves, with the method, URL, status code, and duration, and every log line written while a request is handled carries the same request ID, so the lines of one request can be found together.
We start from a small orders API, add Middleware.requestLogging, tune its log level and logged headers, and then add log annotations with Middleware.logAnnotate. The last section shows where Middleware.tracing fits next to them.
The Problem
A server log is useful when every request leaves a line in it and when the lines of one request can be told apart from the lines of another. Without middleware, each handler has to do both itself: read the clock before and after its work, log the method, the URL, and the status code, and wrap its effect in ZIO.logAnnotate to attach a request ID.
For example, a handler that logs itself looks like this:
import zio._
import zio.http._
val orders: Routes[Any, Response] =
Routes(
Method.GET / "orders" -> handler { (request: Request) =>
val requestId = request.headers.get("X-Request-Id").getOrElse("unknown")
ZIO.logAnnotate("request_id", requestId) {
for {
start <- Clock.nanoTime
response = Response.text("order-1, order-2")
end <- Clock.nanoTime
_ <- ZIO.logInfo(
s"${request.method} ${request.url.encode} ${response.status.code} ${(end - start) / 1000000}ms",
)
} yield response
}
},
)
Every handler repeats the same ten lines around one line of business logic. A handler that someone forgets to wrap writes nothing, a response that fails before the log call is never logged, and changing the log format means editing every handler.
ZIO HTTP moves both jobs into middleware. Middleware.requestLogging writes the request log line, and Middleware.logAnnotate adds annotations to every log line of a request. The handlers keep only their business logic.
Prerequisites
Both middlewares are part of the core zio-http module:
libraryDependencies += "dev.zio" %% "zio-http" % "3.12.0"
They log through ZIO's logging API, so the lines go to whatever logger the application has. The output in this guide comes from ZIO's default console logger, which prints each annotation as a key=value pair. To send the same lines to SLF4J, Logback, or another backend, add a ZIO Logging backend; nothing in the routes changes.
This guide assumes you can define routes and know what a middleware is. If not, start with Routes and Middleware.
The Routes to Log
The examples log a small orders API. The order lookup writes a log line of its own, which later shows which annotations reach the lines a handler writes:
import zio._
import zio.http._
val routes: Routes[Any, Response] =
Routes(
Method.GET / "orders" -> handler(Response.text("order-1, order-2")),
Method.GET / "orders" / int("orderId") -> handler { (orderId: Int, _: Request) =>
ZIO.logInfo(s"Looking up order $orderId").as {
if (orderId == 1) Response.text("order-1") else Response.notFound
}
},
)
Logging Every Request with Middleware.requestLogging
Middleware.requestLogging is a handler aspect that logs one line after each response. We apply it to the routes with @@:
val logged: Routes[Any, Response] =
routes @@ Middleware.requestLogging()
The same aspect is also available as HandlerAspect.requestLogging; Middleware has every HandlerAspect constructor, so either name works.
With the server running, we send two requests: one for an order that exists and one for an order that does not:
$ curl http://localhost:8080/orders/1
$ curl http://localhost:8080/orders/7
The server logs the handler's own line and then the request log line for each of them:
timestamp=2026-12-01T17:48:44.799162431Z level=INFO thread=#zio-fiber-1446475062 message="Looking up order 1" location=example.requestlogging.OrderRoutes.routes file=OrderRoutes.scala line=19
timestamp=2026-12-01T17:48:44.809552898Z level=INFO thread=#zio-fiber-1446475062 message="Http request served" location=example.requestlogging.Step4RequestLoggingExample.app file=Step4RequestLoggingExample.scala line=21 method=GET duration_ms=16 url=/orders/1 response_size=7 status_code=200 request_size=0
timestamp=2026-12-01T17:48:45.212166614Z level=INFO thread=#zio-fiber-1820000596 message="Looking up order 7" location=example.requestlogging.OrderRoutes.routes file=OrderRoutes.scala line=19
timestamp=2026-12-01T17:48:45.227995249Z level=INFO thread=#zio-fiber-1820000596 message="Http request served" location=example.requestlogging.Step4RequestLoggingExample.app file=Step4RequestLoggingExample.scala line=21 method=GET duration_ms=9 url=/orders/7 response_size=0 status_code=404 request_size=0
Each request log line has the message Http request served and these annotations:
| Annotation | Value |
|---|---|
method | The request method |
url | The request URL, with the query string |
status_code | The numeric status code of the response |
duration_ms | Milliseconds from the middleware receiving the request to the handler producing the response |
request_size | The request body size in bytes |
response_size | The response body size in bytes |
The 404 for /orders/7 is logged like any other response, because a route matched and its handler returned the 404. A request that matches no route, such as GET /customers, gets a 404 from the server and leaves no request log line. The sizes are logged only for bodies that are fully in memory; a streaming body has no size annotation.
Runnable version, with the routes from OrderRoutes.scala: Step4RequestLoggingExample.scala
package example.requestlogging
import zio._
import zio.http._
/**
* Log HTTP Requests — The Routes to Log
*
* A small orders API shared by the examples of this guide. The order lookup
* logs a line of its own, so the examples can show which annotations reach the
* handler's log lines. It has no `main`.
*/
object OrderRoutes {
val routes: Routes[Any, Response] =
Routes(
Method.GET / "orders" -> handler(Response.text("order-1, order-2")),
Method.GET / "orders" / int("orderId") -> handler { (orderId: Int, _: Request) =>
ZIO.logInfo(s"Looking up order $orderId").as {
if (orderId == 1) Response.text("order-1") else Response.notFound
}
},
)
}
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file OrderRoutes.scala
// Run from this folder: scala-cli run Step4RequestLoggingExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.requestlogging.Step4RequestLoggingExample"
package example.requestlogging
import zio._
import zio.http._
/**
* Log HTTP Requests — Logging Every Request with `Middleware.requestLogging`
*
* Serves the orders API on port 8080 and logs one line for every request it
* serves, with the method, URL, status code, and duration.
*/
object Step4RequestLoggingExample extends ZIOAppDefault {
val app: Routes[Any, Response] =
OrderRoutes.routes @@ Middleware.requestLogging()
val run = Server.serve(app).provide(Server.default)
}
Choosing the Log Level and the Logged Headers
By default, every request is logged at the INFO level and no headers are logged. Middleware.requestLogging takes parameters for both. level is a function from the response status to a LogLevel, and loggedRequestHeaders and loggedResponseHeaders name the headers to add as annotations:
val requestLogging =
Middleware.requestLogging(
level = status => if (status.isError) LogLevel.Warning else LogLevel.Info,
loggedRequestHeaders = Set(Header.UserAgent),
loggedResponseHeaders = Set(Header.ContentType),
)
val tuned: Routes[Any, Response] =
routes @@ requestLogging
Now client and server errors are logged at WARN, and each line names the client and the response type:
timestamp=2026-12-01T17:48:58.424449042Z level=INFO thread=#zio-fiber-120814051 message="Looking up order 1" location=example.requestlogging.OrderRoutes.routes file=OrderRoutes.scala line=19
timestamp=2026-12-01T17:48:58.429925182Z level=INFO thread=#zio-fiber-120814051 message="Http request served" location=example.requestlogging.Step5CustomizedLoggingExample.requestLogging file=Step5CustomizedLoggingExample.scala line=22 method=GET duration_ms=24 url=/orders/1 response_size=7 user-agent=curl/8.23.0 status_code=200 request_size=0 content-type=text/plain
timestamp=2026-12-01T17:48:58.827834985Z level=INFO thread=#zio-fiber-1070167386 message="Looking up order 7" location=example.requestlogging.OrderRoutes.routes file=OrderRoutes.scala line=19
timestamp=2026-12-01T17:48:58.836495485Z level=WARN thread=#zio-fiber-1070167386 message="Http request served" location=example.requestlogging.Step5CustomizedLoggingExample.requestLogging file=Step5CustomizedLoggingExample.scala line=22 method=GET duration_ms=4 url=/orders/7 response_size=0 user-agent=curl/8.23.0 status_code=404 request_size=0
Each logged header becomes an annotation whose key is the header name, in lower case for the predefined header types such as user-agent, and whose value is the header value. A header the request or response does not have adds no annotation: the 404 response has no body and no Content-Type, so its line has no content-type.
logRequestBody = true and logResponseBody = true add the bodies themselves, as the request and response annotations. Leave them off in production unless you have checked what the bodies contain: they log passwords, tokens, and personal data as readily as anything else, and large bodies make large log lines.
Runnable version: Step5CustomizedLoggingExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file OrderRoutes.scala
// Run from this folder: scala-cli run Step5CustomizedLoggingExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.requestlogging.Step5CustomizedLoggingExample"
package example.requestlogging
import zio._
import zio.http._
/**
* Log HTTP Requests — Choosing the Log Level and the Logged Headers
*
* Logs client and server errors at the WARN level and successful requests at
* INFO, and adds the `User-Agent` request header and the `Content-Type`
* response header to every request log line.
*/
object Step5CustomizedLoggingExample extends ZIOAppDefault {
val requestLogging =
Middleware.requestLogging(
level = status => if (status.isError) LogLevel.Warning else LogLevel.Info,
loggedRequestHeaders = Set(Header.UserAgent),
loggedResponseHeaders = Set(Header.ContentType),
)
val app: Routes[Any, Response] =
OrderRoutes.routes @@ requestLogging
val run = Server.serve(app).provide(Server.default)
}
Adding a Request ID with Middleware.logAnnotate
Middleware.logAnnotate runs each request's handler inside ZIO.logAnnotate, so every log line written while the request is handled carries the given annotations. The simplest form takes a key and a value; the form that takes a Request => Set[LogAnnotation] function derives the annotations from each request. We use the second form to read a request ID from the X-Request-Id header, or make a new one when the client sends none:
import java.util.UUID
val requestId: Middleware[Any] =
Middleware.logAnnotate { (request: Request) =>
val id = request.headers.get("X-Request-Id").getOrElse(UUID.randomUUID().toString)
Set(LogAnnotation("request_id", id))
}
val annotated: Routes[Any, Response] =
routes @@
Middleware.requestLogging() @@
requestId @@
Middleware.logAnnotate("service", "orders")
The order of the @@ calls matters. In routes @@ a @@ b, the middleware b is the outer one: it runs first on the request and sees everything a logs. The annotation middlewares come after Middleware.requestLogging so that they wrap it, and the request log line is written inside their annotations. With the order reversed, the handler's own lines would carry the request ID but the request log line would not.
We send one request with an X-Request-Id header and one without:
$ curl -H 'X-Request-Id: 3f2c9a1e' http://localhost:8080/orders/1
$ curl http://localhost:8080/orders/7
Each request produces two lines, the first from the handler and the second from the request logging, and all four carry the annotations:
timestamp=2026-12-01T17:49:12.015374306Z level=INFO thread=#zio-fiber-1842259794 message="Looking up order 1" location=example.requestlogging.OrderRoutes.routes file=OrderRoutes.scala line=19 service=orders request_id=3f2c9a1e
timestamp=2026-12-01T17:49:12.028115043Z level=INFO thread=#zio-fiber-1842259794 message="Http request served" location=example.requestlogging.Step6LogAnnotationsExample.app file=Step6LogAnnotationsExample.scala line=31 method=GET duration_ms=16 url=/orders/1 response_size=7 status_code=200 service=orders request_size=0 request_id=3f2c9a1e
timestamp=2026-12-01T17:49:12.434992813Z level=INFO thread=#zio-fiber-1750116411 message="Looking up order 7" location=example.requestlogging.OrderRoutes.routes file=OrderRoutes.scala line=19 service=orders request_id=440e27a8-208e-4653-be3c-8b801e6e7f1e
timestamp=2026-12-01T17:49:12.447543670Z level=INFO thread=#zio-fiber-1750116411 message="Http request served" location=example.requestlogging.Step6LogAnnotationsExample.app file=Step6LogAnnotationsExample.scala line=31 method=GET duration_ms=11 url=/orders/7 response_size=0 status_code=404 service=orders request_size=0 request_id=440e27a8-208e-4653-be3c-8b801e6e7f1e
Both lines of the first request share one request_id, taken from the header. The second request had no X-Request-Id header, so it got a new UUID.
Middleware.logAnnotate has other forms for other sources of annotations:
Middleware.logAnnotateHeaders("X-Request-Id", "X-Tenant")annotates with header values directly, using the header names as keys. A header the request does not have is annotated with an empty value.Middleware.logAnnotateZIO(effect)runs an effect for each request to compute the annotations, for values that come from the environment rather than from the request.
Runnable version: Step6LogAnnotationsExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file OrderRoutes.scala
// Run from this folder: scala-cli run Step6LogAnnotationsExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.requestlogging.Step6LogAnnotationsExample"
package example.requestlogging
import java.util.UUID
import zio._
import zio.http._
/**
* Log HTTP Requests — Adding a Request ID with `Middleware.logAnnotate`
*
* Annotates every log line written while a request is handled, the request log
* line included, with the service name and a request ID. The request ID comes
* from the `X-Request-Id` header, or is a new UUID when the request has none.
*/
object Step6LogAnnotationsExample extends ZIOAppDefault {
val requestId: Middleware[Any] =
Middleware.logAnnotate { (request: Request) =>
val id = request.headers.get("X-Request-Id").getOrElse(UUID.randomUUID().toString)
Set(LogAnnotation("request_id", id))
}
val app: Routes[Any, Response] =
OrderRoutes.routes @@
Middleware.requestLogging() @@
requestId @@
Middleware.logAnnotate("service", "orders")
val run = Server.serve(app).provide(Server.default)
}
Where Tracing Fits
A request log line says that a request happened and how long it took. A trace also groups the log lines of a request under a named span. Middleware.tracing does this with ZIO's own log spans: it runs each request inside a log span named after its method and route pattern, such as GET /orders/{orderId}, and adds the annotations http.method, http.route, and http.target:
val traced: Routes[Any, Response] =
routes @@
Middleware.requestLogging() @@
Middleware.tracing()
The span appears on every log line of the request, with the time spent in it so far:
timestamp=2026-12-01T17:49:24.015371431Z level=INFO thread=#zio-fiber-1879017646 message="Looking up order 1" "GET /orders/{orderId}"=11ms location=example.requestlogging.OrderRoutes.routes file=OrderRoutes.scala line=19 http.method=GET http.route=/orders/{orderId} http.target=/orders/1
timestamp=2026-12-01T17:49:24.024461053Z level=INFO thread=#zio-fiber-1879017646 message="Http request served" "GET /orders/{orderId}"=20ms location=example.requestlogging.Step7TracingExample.app file=Step7TracingExample.scala line=23 method=GET duration_ms=13 url=/orders/1 request_size=0 http.route=/orders/{orderId} http.target=/orders/1 response_size=7 status_code=200 http.method=GET
The http.route annotation holds the route pattern, not the path, so all requests to one route share a value; that makes it a better key than url for grouping requests in a log search.
Middleware.tracing stays inside the process: its spans are log spans, and nothing is sent to a tracing backend. To export traces to an OpenTelemetry backend and follow one request across services, use ZIO Telemetry.
Runnable version: Step7TracingExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file OrderRoutes.scala
// Run from this folder: scala-cli run Step7TracingExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.requestlogging.Step7TracingExample"
package example.requestlogging
import zio._
import zio.http._
/**
* Log HTTP Requests — Where Tracing Fits
*
* Runs every request inside a log span named after its method and route
* pattern, such as `GET /orders/{orderId}`, and annotates its log lines with
* `http.method`, `http.route`, and `http.target`.
*/
object Step7TracingExample extends ZIOAppDefault {
val app: Routes[Any, Response] =
OrderRoutes.routes @@
Middleware.requestLogging() @@
Middleware.tracing()
val run = Server.serve(app).provide(Server.default)
}
Running the Examples
All runnable code from this guide is in zio-http-example/src/main/scala/example/requestlogging/. Run any file from that folder with scala-cli run <File>.scala, or from the repository root with sbt "zioHttpExample/runMain example.requestlogging.<ObjectName>". Each example starts a server on port 8080; send it the curl requests above and watch the server's console.
Going Further
- HandlerAspect lists the parameters of
requestLogging. - Middleware lists every form of
Middleware.logAnnotate. - Client shows
ZClientAspect.requestLogging, which logs the requests a ZIO HTTP client sends. - Logging in the ZIO documentation covers log levels, spans, and annotations in ZIO itself.