August 31, 2026

Stop Treating Logs as Text Files: Debugging with systemd-journald

When a service fails on an embedded Linux device, the first reaction is often: “Which log file should I open?”

That question comes from a useful but incomplete logging model. It assumes logs are streams of text appended to files and searched later with grep. On a systemd-based system, a better first question is:

Which service, boot, process, time window, priority and service invocation am I trying to understand?

systemd-journald collects log records from sources such as the kernel, the syslog API and system services. It stores structured journal entries with metadata that can be queried through journalctl. The message text still matters, but it is only one field in a larger record.

For a long-running daemon, this changes the debugging workflow. Instead of guessing which file might contain the relevant lines, you can narrow the evidence to this unit, in this boot, around this failure time, at this severity and, on newer systemd versions, from this specific service invocation.

In the first article, Systemd Is More Than systemctl: A Practical Map of the Linux System Manager, we built the broad map: units, lifecycle, logging, identities, filesystem state, cgroups and activation. In the second, How Systemd Thinks: Units, Dependencies, Ordering, and Boot Failures, we moved into the unit graph and separated dependencies from ordering. The third, Writing Production-Grade Systemd Services: Readiness, Restart, and Shutdown, defined the lifecycle contract around readiness, recovery and graceful shutdown.

This fourth article moves from lifecycle to evidence: how to reconstruct what a service actually did when that lifecycle goes wrong.

Series context

The goal here is not to memorize every journalctl switch. It is to build a repeatable debugging workflow: narrow the unit, boot, time and severity first, then use structured fields and service-specific context when the investigation needs to go deeper.

ttimeline

A journal entry is more than a log line


A traditional log line often gives you only what the application decided to print:

Jun 26 09:14:37 target device-daemon[421]: failed to connect

That is readable, but it forces the reader to infer most of the context. Was this from the current boot? Which unit launched the process? Was PID 421 later restarted? Did the failure happen before or after the service reported readiness? Is this a warning or a fatal error? Did the message come from the service, from systemd about the service, or from a core dump handler?

A journal entry can carry message text and metadata. Common fields include:

  • MESSAGE — the human-readable message.
  • PRIORITY — syslog severity.
  • _SYSTEMD_UNIT — the systemd unit associated with the process.
  • _BOOT_ID — the boot in which the record was created.
  • _PID, _COMM and _EXE — process identity details.
  • SYSLOG_IDENTIFIER — a stable identifier used to label messages.
  • _SYSTEMD_INVOCATION_ID — a runtime identity that distinguishes one service start from another.

Not every entry contains every field, and available metadata depends on how the message reached the journal. But the model is important: the journal stores records, not just lines.

You can inspect the full metadata of an entry with verbose output:

journalctl -u device-daemon.service -b -o verbose -n 1

This is worth doing at least once on a development target. It makes the invisible context visible and helps you understand which fields are available for filtering later.

Practical rule

Write a clear message for humans. Use journal metadata to answer the questions humans would otherwise try to reconstruct from timestamps and text parsing.

onemessage

Where service logs come from


For a systemd-managed service, the easiest logging path is usually already present: service stdout and stderr are connected to the journal by default unless the unit or manager configuration overrides that behavior. A daemon can therefore become observable without opening, rotating and permission-managing its own private text file.

You can still make that contract explicit when it improves readability:

[Service]
ExecStart=/usr/bin/device-daemon
StandardOutput=journal
StandardError=journal
SyslogIdentifier=device-daemon

The two Standard* lines are commonly redundant on a normal system service, but documenting them can be useful in a product unit that is reviewed independently from manager defaults. SyslogIdentifier= gives messages written through the standard streams a stable human-facing label instead of relying only on the executable name.

Messages can also reach journald through:

  • The kernel log buffer.
  • The traditional syslog API used by C and C++ libraries.
  • Native libsystemd journal APIs that attach structured fields.
  • Tools such as systemd-cat, useful when wrapping a command that already writes to standard output.
  • Systemd itself, which reports starts, exits, timeouts, watchdog failures and restart decisions.

This last source is easy to underestimate. If a service exits, systemd can emit records that explain the lifecycle decision even when the application produced no useful message of its own.

For a quick wrapper around an existing command-line diagnostic tool:

vendor-diagnostic --full 2>&1 | \
  systemd-cat -t vendor-diagnostic -p info

This is useful for experiments and integration work. For a real daemon, do not make the business logic depend on successful log delivery. Logging is evidence and observability. It must not become the reason an update operation, hardware state machine or shutdown path fails.

The five journalctl commands worth learning first


You do not need to memorize every journalctl option. A small set covers most service investigations.

QuestionCommandWhy it helps
What happened to this service in this boot?journalctl -u device-daemon.service -bScopes logs to one unit and the current boot.
What happened immediately before and after the current failure?journalctl -u device-daemon.service -b -n 200Starts with a manageable tail instead of pages of history.
What is happening right now?journalctl -u device-daemon.service -fFollows new messages as they arrive.
Did the service fail in the previous boot?journalctl -u device-daemon.service -b -1Compares this boot with the previous retained boot.
What errors did this unit report?journalctl -u device-daemon.service -b -p warningShows warnings and all more severe priorities while filtering lower-priority noise.

In normal debugging, add --no-pager when you want output that can be copied, saved or used in automation:

journalctl -u device-daemon.service -b -n 200 --no-pager

For timings that need more precision than the default display:

journalctl -u device-daemon.service \
  -b \
  -o short-precise \
  --no-pager

This becomes especially useful when you are comparing an application timeout, a D-Bus call, a network reconnect and a systemd lifecycle event that all happened within a few seconds.

Do not begin with journalctl | grep

Text search is still useful sometimes, but it should not be your first filter. Start with unit, boot, time and priority because those are stable structured dimensions. Search message text after you have reduced the relevant scope.

Debug one failure from the unit outward


Suppose a device service did not come up after boot. The wrong response is to read every message from every process until something looks suspicious. Start with the unit that owns the feature.

# 1. Read systemd's current view of the unit.
systemctl status device-daemon.service --no-pager

# 2. Read the unit's logs from the current boot.
journalctl -u device-daemon.service -b -n 200 --no-pager

# 3. Narrow to the time when the failure was observed.
journalctl -u device-daemon.service \
  --since "2026-06-26 09:10:00" \
  --until "2026-06-26 09:15:00" \
  --no-pager

# 4. Ask whether it happened before too.
journalctl --list-boots
journalctl -u device-daemon.service -b -1 --no-pager

This sequence answers four different questions:

  1. What state does systemd report now?
  2. What did the service and service manager report during this boot?
  3. What happened around the exact time the failure became visible?
  4. Is this a new regression or a repeatable problem across boots?

For a unit that restarts quickly, the important story is often not one message. It is the timeline:

  • The service starts.
  • It logs an initialization failure.
  • It exits with a failure status.
  • Systemd schedules a restart.
  • The same sequence repeats until start-rate limiting stops it.

That is why journal scope matters. It lets you see the application error and the systemd recovery decision together.

read a restarloopasonestory

Use boot IDs and time windows deliberately


Boot boundaries are one of the journal’s most valuable features. A service that fails before a reboot and then succeeds after it should not be analyzed as though all records belong to one uninterrupted timeline.

List the retained boots first:

journalctl --list-boots

Then select the current boot with -b, the previous retained boot with -b -1, or another boot from the listed history.

Time filtering is just as important for incidents that do not require a reboot:

journalctl -u device-daemon.service \
  --since "15 minutes ago" \
  --until "now" \
  --no-pager

Or use precise absolute timestamps when correlating the journal with a test report, a CAN trace, a network capture or a customer issue report.

Filter one service invocation when restarts blur the timeline

A boot can contain many starts of the same service. If a daemon crashes and restarts repeatedly, filtering only by unit and boot can still mix several runtime cycles together.

On systemd 257 and newer, journalctl can filter by service invocation directly. With a unit selected, -I means the latest invocation:

journalctl -u device-daemon.service -b -I --no-pager

Older systemd versions still expose _SYSTEMD_INVOCATION_ID in journal metadata when available. Inspect an entry with -o verbose, then filter on the field explicitly:

journalctl _SYSTEMD_INVOCATION_ID=<id> --no-pager

Why invocation matters

A PID can be reused and a unit can restart several times in one boot. The invocation ID gives one runtime cycle of the unit a stable identity, which is exactly the scope you want when reconstructing a restart loop.

Previous-boot logs are not guaranteed

journalctl -b -1 only works when the previous boot’s journal was retained. On a volatile journal, logs are kept under runtime storage and disappear on reboot. That can be acceptable for development images, but it is usually a poor incident-debugging story for a field device.

Persistent logs are a product decision, not a default checkbox


There are two local journal storage modes that matter most in practice, and deployed products may also export selected evidence off-device:

Storage choiceTypical locationBenefitCost / risk
Volatile journal/run/log/journalNo persistent flash use; simple for disposable development sessions.Logs vanish on reboot; poor evidence after crash or watchdog reset.
Persistent journal/var/log/journalPrevious boots can be inspected; much better for field diagnosis.Consumes writable storage and must have bounded retention.
Forwarded or exported logsRemote collector, support bundle or product telemetryPreserves evidence when the device storage is unavailable or later overwritten.Needs transport, privacy review, bandwidth policy and failure handling.

With the usual Storage=auto behavior, persistence depends on whether /var/log/journal exists. Even with persistent storage enabled, journald initially uses runtime storage during early boot and later flushes records to persistent storage when it becomes available. The exact image behavior should be verified on the target, not assumed from a desktop distribution.

For a product image, use a drop-in rather than editing a vendor configuration file directly:

# /etc/systemd/journald.conf.d/60-product-storage.conf
[Journal]
Storage=persistent
SystemMaxUse=128M
SystemKeepFree=64M
RuntimeMaxUse=32M

The numbers above are examples, not recommended defaults. The correct limits depend on the writable partition size, flash endurance, expected boot frequency, log rate, support process and whether the device can upload a diagnostic bundle before older evidence is overwritten.

Inspect actual journal usage:

journalctl --disk-usage

Manual vacuum commands can remove archived journal files, but they are not a substitute for a product retention policy:

journalctl --vacuum-size=128M
journalctl --vacuum-time=14d

Do not treat log retention as harmless

Unlimited persistent logs can consume the writable partition. Overly aggressive retention can erase the only evidence of an intermittent failure. Decide which failures must survive reboot, how much data is acceptable, and how a support engineer gets that data off the device.

volatilepersistentexported

Rate limiting protects the target, but can hide the symptom


A broken loop can write thousands of messages per second. On a workstation that is annoying. On a constrained target it can consume CPU, fill a writable partition, hide the original error under repeated noise and make the failure harder to reproduce.

Journald supports rate limiting. journald.conf defines global defaults that are enforced per service, for example:

# /etc/systemd/journald.conf.d/70-rate-limit.conf
[Journal]
RateLimitIntervalSec=30s
RateLimitBurst=10000

On systemd 253 and newer, a unit can also override those defaults for one service with LogRateLimitIntervalSec= and LogRateLimitBurst=:

[Service]
LogRateLimitIntervalSec=30s
LogRateLimitBurst=2000

The correct values depend on the system, service and systemd version, so inspect the shipped configuration and test a deliberately noisy component on real hardware. The important operational fact is simpler: repeated messages may be suppressed, and the right budget for one daemon may be wrong for another.

That means rate limiting is not an excuse for poor application logging. The application should also avoid logging the same recoverable condition in every iteration of a hot loop.

  • Log the first failure with enough context to diagnose it.
  • Log state transitions, not every successful poll.
  • Use counters or periodic summaries for repeated transient failures.
  • Escalate priority when the component crosses a meaningful failure threshold.

A message such as “socket read failed” repeated fifty thousand times is not observability. It is a denial-of-service attack performed by your own error path.

From C++ text logs to structured events


Writing useful messages to stderr is a good baseline. It is portable, easy to test and normally reaches the journal when the process runs as a systemd service.

#include <cerrno>
#include <cstring>
#include <iostream>

void reportOpenFailure(const char* path)
{
    std::cerr << "Cannot open configuration file '"
              << path
              << "': "
              << std::strerror(errno)
              << '\n';
}

That may be enough for a small daemon. But a product component often needs stable context that a support tool can filter without parsing English sentences. This is where the native journal API becomes useful.

#include <systemd/sd-journal.h>
#include <syslog.h>

#include <string>

void reportVerificationFailure(const std::string& updateId,
                               const std::string& reason)
{
    sd_journal_send(
        "MESSAGE=Firmware verification failed",
        "PRIORITY=%i", LOG_ERR,
        "SYSLOG_IDENTIFIER=device-updater",
        "GR8_COMPONENT=update-verifier",
        "GR8_UPDATE_ID=%s", updateId.c_str(),
        "GR8_FAILURE_REASON=%s", reason.c_str(),
        "MESSAGE_ID=8d48a95f16e64cbcb57b3a0b0ea4a621",
        nullptr);
}

Custom journal fields should be stable, uppercase names that do not begin with an underscore. The underscore namespace is reserved for trusted metadata added by the journal and system components.

Now the failure can be queried by meaning instead of by sentence wording:

journalctl \
  GR8_COMPONENT=update-verifier \
  GR8_UPDATE_ID=2026.06.26.1 \
  --no-pager

The fixed MESSAGE_ID is also useful when the human wording needs to improve over time but the event category should remain stable for tooling and support procedures. Generate a real identifier once for each stable event type, for example with systemd-id128 new, then keep that ID unchanged while the human-readable message evolves.

Design principle

Use the message for a person reading a failure at 2 a.m. Use fields for the values a tool, support bundle or test report must filter and correlate reliably.

A minimal CMake integration for the native API can use pkg-config:

find_package(PkgConfig REQUIRED)
pkg_check_modules(SYSTEMD REQUIRED IMPORTED_TARGET libsystemd)

target_link_libraries(device-daemon
    PRIVATE
        PkgConfig::SYSTEMD
)

Do not make every log statement a direct dependency on libsystemd by default. A logging wrapper can keep application code independent and use structured journal fields only where they provide real operational value.

textforpeoplefieldsfortools

A crash is a logging event, but not only a logging event


When a service crashes, the journal is usually where you begin. It can show the unit start, the last application messages, the exit status, systemd’s restart decision and, when configured, coredump metadata.

On systems that include systemd-coredump and allow core dumps, these commands can be useful:

coredumpctl list device-daemon
coredumpctl info device-daemon

Whether core dumps are available, where they are stored and how much storage they may consume are separate product decisions. A core dump can be very valuable for an intermittent production crash, but it can also contain sensitive process memory and consume significant space.

For that reason, a production crash strategy should answer more than “can we enable coredumps?”:

  • Which components may generate a dump?
  • Where does the dump go on a storage-constrained device?
  • Who is allowed to retrieve it?
  • How is it correlated with the corresponding journal and software version?
  • Does the support process handle the privacy implications of process memory?

Logging mistakes that make field debugging harder


  • Logging only “failed”. Include the operation, relevant identifier and failure reason. “Connection failed” is less useful than “Provisioning connection to broker A failed: certificate chain rejected”.
  • Parsing messages that should be fields. If a support tool must repeatedly extract update ID, modem ID, interface name or transaction ID from English text, make it a stable structured field.
  • Logging secrets. Never write credentials, access tokens, private keys, raw authentication headers or full provisioning payloads into the journal.
  • Assuming a previous boot exists. Test retention after a real reboot. Do not discover during an incident that logs were volatile.
  • Turning every debug trace on permanently. High-volume logs cost storage, CPU and attention. Keep default logs useful; expose temporary diagnostic levels deliberately.
  • Ignoring journal rate-limit messages. If logs were suppressed, the missing line may be part of the symptom. Fix the repetitive failure loop rather than only increasing limits.
  • Using the journal as a database. The journal is excellent evidence and event context. It is not a replacement for durable domain state, metrics, audit records or a product telemetry protocol.

A practical journal checklist for every daemon


  1. Can I read this service’s logs with journalctl -u <unit> -b?
  2. Does the unit have a clear, stable SyslogIdentifier= when the executable name is not enough?
  3. Do startup, readiness, shutdown and unrecoverable failure paths log enough context?
  4. Can I tell which boot and which service start produced the failure?
  5. Are product-critical IDs available as structured fields instead of only inside message text?
  6. Have I tested log persistence after a real reboot on the target hardware?
  7. Are journal size, retention and rate-limit settings appropriate for the writable storage budget?
  8. Does the component avoid writing secrets and personal data into logs?
  9. Can a support engineer collect a focused unit journal without dumping the entire device log history?

The key idea


If you remember only one thing, remember this:

Tip

systemd-journald turns service logs into queryable evidence. Start debugging by narrowing the unit, boot, time and severity. Then make your daemon emit messages and fields that answer the next question before somebody has to ask it.

Good logging does not mean printing more text. It means leaving enough structured evidence to reconstruct what happened: which unit ran, in which boot, during which invocation, for which transaction and why it failed.

That is why journald is especially useful in embedded Linux. A device often fails far away from the developer who built it. A useful journal lets the device preserve enough context for somebody else to reconstruct the failure later.

The next article moves from evidence to the filesystem state around a service: Runtime Directories Done Right: systemd-tmpfiles and systemd-sysusers.