Structured logs with Spring Boot, Alloy and Loki
docker logs | grep is a good tool until you need yesterday's logs, a container that has been recreated, or only the errors from one component. This site's deployment sends every container's logs to a central Loki that Grafana can query. The setup is small, and most of the useful decisions are about what not to do.
JSON from Spring Boot, in one setting
Since version 3.4, Spring Boot can write structured logs without any extra dependency or a custom encoder. This site turns it on in compose.yaml:
environment:
# One JSON object per line, so Loki can filter by level.
LOGGING_STRUCTURED_FORMAT_CONSOLE: ecs
ecs is the Elastic Common Schema. Spring Boot also ships logstash and gelf. Because the setting is only in the container's environment, logs stay as readable plain text when running from an IDE or Maven.
An entry then looks something like this, on a single line:
{"@timestamp":"2026-11-08T10:00:00.123Z","log":{"level":"WARN","logger":"dev.suleimanov.contact.telegram.TelegramNotificationJob"},"message":"Telegram send failed","ecs":{"version":"8.11"}}
The important part is that a stack trace is now a field inside one entry. With plain text, each line of a stack trace is a separate log entry, and searching for an exception gives you fragments.
To add your own searchable fields, use SLF4J's fluent API rather than building them into the message:
log.atInfo()
.addKeyValue("messageId", message.id())
.log("Contact message sent");
Alloy collects, Loki stores
Grafana Alloy runs next to the application and reads from the Docker socket, so the application doesn't know anything about Loki. If Loki is unavailable, the application carries on, and Alloy retries for a while.
The configuration is short:
discovery.docker "containers" {
host = "unix:///var/run/docker.sock"
}
discovery.relabel "containers" {
targets = []
rule {
source_labels = ["__meta_docker_container_name"]
regex = "/(.*)"
target_label = "container"
}
}
loki.source.docker "containers" {
host = "unix:///var/run/docker.sock"
targets = discovery.docker.containers.targets
relabel_rules = discovery.relabel.containers.rules
forward_to = [loki.write.central.receiver]
}
loki.write "central" {
endpoint {
url = sys.env("LOKI_URL")
}
external_labels = {host = sys.env("LOKI_HOST_LABEL")}
}
Two practical details are worth copying:
- Alloy has a volume for its storage path, which records how far it has read each container's log. Without it, recreating the agent can send logs again or skip some.
- Alloy runs in its own compose project. Otherwise, the application's
docker compose up --remove-orphanswould treat it as an orphan and remove it during a deploy.
Since it runs on a machine with limited memory, the agent also gets a container limit of 256 MB and GOMEMLIMIT=200MiB, so that the Go runtime collects garbage before the limit would kill it.
The mistake everyone makes: too many labels
Loki doesn't index the contents of logs the way Elasticsearch does. It indexes labels only, and stores each unique combination of labels as a separate stream. That makes it cheap to run, and it also means label choice is the most important decision in the whole setup.
Good labels have few possible values: host, container, service, maybe environment. This site uses just host and container.
Bad labels are anything unbounded: user ID, request ID, IP address, trace ID. Each new value creates a new stream, with its own chunks and index entries. Performance gets worse and storage climbs, a problem known as high cardinality.
The log level is a tempting label, but you don't need it. Loki can filter inside the JSON at query time.
Querying with LogQL
Choose streams with labels first, then filter:
{container="suleimanov-server-1"} | json | log_level="ERROR"
The json parser flattens nested fields with underscores, so log.level becomes log_level. To search a message:
{host="web-1"} |= "Telegram" | json | log_level=~"WARN|ERROR"
|= is a fast text match. Put it before | json, so that Loki doesn't parse lines it's going to discard anyway.
LogQL can also make numbers from logs, which is useful for alerting:
sum by (container) (count_over_time({host="web-1"} | json | log_level="ERROR" [5m]))
What not to log
Central logs get retained, shared and queried by more people than the application's database. Passwords and tokens must never go there, and it's worth being careful with personal data too. On the contact form, for example, the job logs a message's ID when it's sent, and not its contents. Set a retention period in Loki, too. Logs you keep forever are a cost and a liability.
The result is a modest setup: one setting in the application, a short agent configuration and a couple of labels. In exchange, the question "what happened at 20:37?" takes one query, even when the container that logged it no longer exists.