Haskell Structured Logging for Production Services
Your Haskell service crashed at 03:12, and the only clue is a wall of putStrLn output with no request id, no timestamp precision and no way to filter it.

Your Haskell service crashed at 03:12, and the only clue is a wall of putStrLn output with no request id, no timestamp precision and no way to filter it. Haskell structured logging fixes that by turning every log line into a record with named fields, so your log store can answer "show me every failed payment for customer 4417 in the last hour" instead of making you grep by hand.
Below: picking a library, the fields every line needs, carrying request context, and where logging quietly costs you performance. The examples assume a web or worker service built on a ReaderT over IO.
What Haskell structured logging actually means
A plain log line is a string written for a human. A structured log line is a small object written for a machine first: a timestamp, a severity, a message, and a set of key value pairs such as request_id, user_id, route and duration_ms. In practice that object is serialized as one JSON document per line, because every log shipper and query engine understands newline delimited JSON.
The win is not prettier output. The win is that you stop encoding facts inside sentences. "Payment 9921 failed after 3 retries" becomes a message of "payment failed" with payment_id 9921 and attempts 3 as separate fields. You can count, group and alert on those fields without writing a regular expression that breaks the day someone rewords the message.
Choosing a logging library
Four libraries cover almost every production codebase. They differ mostly in how they pass context around and how much they ask your application monad to change.
| Library | Context model | JSON output | Best fit |
|---|---|---|---|
| katip | Namespaces plus typed context, carried in a Katip or KatipContext class | Built in through scribes | Services that want rich context and several outputs |
| co-log | A LogAction value you pass or store in your environment | Bring your own encoder | Teams that prefer explicit values over type classes |
| monad-logger | MonadLogger class, text messages with a source tag | Not by default, needs an adapter | Projects already on persistent or yesod |
| fast-logger | No context at all, just a fast buffered writer | You write the bytes | The output layer underneath one of the others |
If you are starting fresh and want structure on day one, katip is the shortest path. Its scribes handle JSON to stdout, file rotation and Elasticsearch, and its context model was designed for exactly this problem. If your team dislikes adding another class constraint to every function, co-log gives you the same result with a plain record field holding the log action.
The fields every log line should carry
Structure only helps if the fields are consistent across the whole service. Agree on a short required set and enforce it in one place, usually the function that builds your logger at startup.
- timestamp in UTC with millisecond precision.
- level from a fixed set: debug, info, warning, error. Four levels are enough.
- service and version, so a deploy that changed behavior is visible in the logs without cross referencing the release history.
- request_id or job_id, generated at the edge and attached to everything that request touches.
- message, short and stable. Treat it like an event name, not a sentence.
Everything else is per event: durations in milliseconds as numbers, ids as strings, counts as integers. Pick one naming convention, snake_case is the most common, and do not mix it with camelCase from Aeson's default record encoding. A field called userId in one module and user_id in another splits your queries in half.
Carrying request context without threading arguments
The common mistake is passing a request id as an argument into every function. It works until someone adds a helper that forgets it and those lines go dark.
The better pattern is to keep the context in your application environment and extend it locally. With katip you call katipAddContext around a block of code, and every log call inside that block includes the added fields. With co-log you do the same by building a new LogAction with cmap that enriches each message, then running the inner code with a modified environment through local.
Concretely, the request handler middleware should do three things in order:
- Read an incoming request id header, or generate a new UUID if there is none.
- Add request_id, route and method to the logging context for the rest of the handler.
- Log one summary line at the end with status code and duration_ms, even when the handler throws.
That last line is the one you will query most. Wrap it with a bracket or finally style combinator so an exception still produces it, then rethrow. If you already run background workers, the same idea applies per job, which pairs naturally with the patterns in retrying flaky calls with exponential backoff, where each attempt should log its attempt number as a field.
Where the common advice gets it wrong
You will often read that you should log everything at debug level in production and filter later, because storage is cheap. In a Haskell service that advice has a hidden cost beyond the storage bill.
Log arguments are often built lazily. A debug line that renders a large Map or a full request body creates thunks, and if the logger's level check happens after the message is constructed, you pay the allocation on every call even when the line is discarded. Under load we have seen a single chatty debug call add 8 to 12 percent to allocation rate in the +RTS -s report, which is the kind of number covered in reading GHC's runtime statistics before tuning the GC.
Worse, a log context that holds onto a big structure keeps it alive for as long as the context lives. That is a classic source of slow memory growth, and it looks exactly like the problems described in finding and fixing a Haskell space leak in production. The fix is simple: run production at info, make sure level checks happen before message construction, and log sizes or hashes instead of whole payloads. Log the length of a list, not the list, and use strict Text in field types.
Output, buffering and shutdown
Write JSON to stdout and let the platform ship it. Container runtimes, systemd and most hosting platforms already collect stdout, and writing directly to a network log sink from inside the process adds a failure mode you do not need.
Buffer the writes. fast-logger and katip's handle scribe both batch output, which matters once you pass a few thousand lines per second. The trade off is that a buffered logger can lose its final lines if the process exits without flushing. Close your scribes or flush the logger set as part of shutdown, after the HTTP server has stopped accepting requests and in-flight handlers have finished. If the last thing you see before a crash is silence, a missing flush is the first suspect.
Frequently asked questions
Which Haskell logging library is best for JSON logs?
katip is the most complete choice for JSON logs out of the box, because its scribes encode structured context directly. co-log works just as well if you prefer explicit values over type classes, but you write a small JSON encoder yourself. Both sit comfortably on top of fast-logger style buffered output.
How do I add a request id to every log line in Haskell?
Generate or read the id in middleware, then add it to the logging context held in your environment for the rest of the request. In katip that is katipAddContext, and in co-log you build an enriched LogAction and run the handler with local. Avoid passing the id as an argument to every function.
Does logging slow down a Haskell service?
Logging at info level with buffered output is cheap for most services. The slowdown comes from building large or lazy messages that are then discarded, and from contexts that keep big structures alive. Check levels before constructing messages and log small, strict values.
More in Systems
Systems
Haskell Bounded Concurrency for Background Workers
A worker that drains a job queue is the first Haskell service most teams ship, and it is also the first one that gets killed by...
Systems
Haskell Health Check Endpoints for Kubernetes Probes
A student of mine shipped her first Haskell service to a small Kubernetes cluster last spring, and it restarted itself 41 times...
Systems
Haskell Retry With Exponential Backoff for Flaky Services
Your Haskell service calls a payment API, a Postgres replica, or an S3 bucket, and roughly one request in two hundred fails...