Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@emlun
Last active February 13, 2022 17:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emlun/6f847a74e0136188d7a4 to your computer and use it in GitHub Desktop.
Save emlun/6f847a74e0136188d7a4 to your computer and use it in GitHub Desktop.
Journal filtering skeleton

Journal filtering skeleton

Proof of concept on how one can monkey patch any systemd service and filter its journal output.

By default, systemd services connect the executable's STDOUT to the journal. If the executable doesn't provide a way to configure its output, you're left with redirecting the output somewhere else. And since the options for redirecting systemd services' output are very limited, one of the simplest ways to do it is to replace the executable with a shell script that calls it instead.

This method does have difficulties with quoted parameters, though, a illustrated by the example. It should work fine as long as you don't need quotes though.

Quick-and-dirty setup

log-and-filter.sh   ->   /etc/log-and-filter.sh
test.service        ->   /etc/systemd/user/test.service

Run it:

$ systemctl --user daemon-reload
$ systemctl --user start test.service

Look at the output:

$ systemctl --user status test.service # Verify that only the 1 and 3 lines
                                       # show up in the journal
$ cat /tmp/test.log # Verify that the file contains all output
#!/bin/bash
logfile="$1"
shift
filter() {
exec grep -E "1|3"
}
$@ | tee -a "$logfile" | filter
[Unit]
Description=Prints 1, 2, 3, 4, 5 each on its own line.
[Service]
Type=oneshot
ExecStart=/etc/log-and-filter.sh /tmp/test.log /usr/sbin/echo -e "1\\n2\\n3\\n4\\n5"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment