How to Write Logs to Systemd Journal Using syslog, printf, and sd_journal in Linux
This article demonstrates three methods for sending logs to the systemd journal—using the libc syslog() function, capturing stdout/stderr via printf(), and employing the native systemd sd_journal API—complete with C, Python, and Bash examples, service setup, and log filtering techniques.
With systemd becoming the mainstream init system, its journal feature has grown to manage system logs. This article introduces three ways to write logs to the systemd journal.
Logs emitted via the libc syslog() function.
Logs printed with printf().
All output sent to STDOUT/STDERR by a service process.
Demo environment: Ubuntu 16.04.
syslog()
Function declaration:
#include <syslog.h>
void syslog(int priority, const char *message, ...);Create clog.c:
#include <syslog.h>
int main(int argc, char *argv[]) {
syslog(LOG_NOTICE, "C Hello World");
return 0;
}Compile and run: $ gcc -Wall clog.c -o clog Running the program shows the log in journal -f output (three entries because the program was executed three times).
Log severity LOG_NOTICE corresponds to level 5. Common severity macros:
#define LOG_EMERG 0 /* system is unusable */
#define LOG_ALERT 1 /* action must be taken immediately */
#define LOG_CRIT 2 /* critical conditions */
#define LOG_ERR 3 /* error conditions */
#define LOG_WARNING 4 /* warning conditions */
#define LOG_NOTICE 5 /* normal but significant condition */
#define LOG_INFO 6 /* informational */
#define LOG_DEBUG 7 /* debug-level messages */Python equivalent:
#!/usr/bin/env python
import syslog
syslog.syslog('P Hello World')Execute:
$ python plog.pyViewing logs in JSON format:
printf()
The journal captures everything a service writes to STDOUT/STDERR, including C printf, Python print, and shell echo. This works only when the program runs as a systemd service.
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("C Print Hello World.
");
return 0;
}Compile: $ gcc -Wall printlog.c -o printlog Create a simple service /lib/systemd/system/testlog.service:
[Unit]
Description=test log
[Service]
ExecStart=/home/nick/projects/journaldemo/printlog
[Install]
WantedBy=multi-user.targetReload and start the service:
$ sudo systemctl daemon-reload
$ sudo systemctl start testlog.serviceThe journal captures the STDOUT output:
By default the log level is LOG_INFO (6). The JSON view shows the priority:
Custom log levels can be set by prefixing messages with <N> where N is the desired priority:
#include <stdio.h>
#define PREFIX_NOTICE "<5>"
int main(void) {
printf(PREFIX_NOTICE "Hello World
");
fprintf(stderr, "<3>Hello Error
");
return 0;
}Python example:
#!/usr/bin/env python
print '<5>Hello World'Bash example:
#!/bin/bash
echo "<5>Hello World"Systemd Journal Library
Systemd provides a native C library ( systemd/sd-journal.h) for sending logs directly to the journal. Install with sudo apt install libsystemd-dev on Ubuntu 16.04.
#include <systemd/sd-journal.h>
int sd_journal_print(int priority, const char *format, ...);
int sd_journal_send(const char *format, ...);Simple example using sd_journal_print:
#include <systemd/sd-journal.h>
int main(int argc, char *argv[]) {
sd_journal_print(LOG_NOTICE, "Hello World");
return 0;
}This method records the log with explicit priority and includes source location information, aiding debugging.
Custom fields can be added with sd_journal_send:
#include <systemd/sd-journal.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
sd_journal_send(
"MESSAGE=Hello World!",
"MESSAGE_ID=52fb62f99e2c49d89cfbf9d6de5e3555",
"PRIORITY=5",
"HOME=%s", getenv("HOME"),
"TERM=%s", getenv("TERM"),
"PAGE_SIZE=%li", sysconf(_SC_PAGESIZE),
"N_CPUS=%li", sysconf(_SC_NPROCESSORS_ONLN),
NULL);
return 0;
}These custom fields can be filtered with journalctl.
Python bindings are also available via the systemd module:
from systemd import journal
journal.send('Hello world')
journal.send('Hello, again, world', FIELD2='Greetings!', FIELD3='Guten tag')After installing the module ( pip install systemd) and running the script, the messages appear in the journal, and the custom fields are visible in the JSON view.
Summary
This article covered common ways to write logs to the systemd journal, helping developers design effective logging strategies and leverage journal features for troubleshooting.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
