bashloggingstdoutstderrsystemd-journald

Is there a way to redirect all stdout and stderr to systemd journal from within script?


I like the idea of using systemd's journal to view and manage the logs of my own scripts. I have become aware you can log to journal from my user scripts on a per message basis..

echo 'hello' | systemd-cat -t myscript -p emerg

Is there a way to redirect all messages to journald, even those generated by other commands? Like..

exec &> systemd-cat

Update:

Some partial success. Tried Inian's suggestion from terminal.

~/scripts/myscript.sh 2>&1 | systemd-cat -t myscript.sh

and it worked, stdout and stderr were directed to systemd's journal. Curiously,

~/scripts/myscript.sh &> | systemd-cat -t myscript.sh

didn't work in my Bash terminal.

I still need to find a way to do this inside my script for when other programs call my script.

I tried..

exec 2>&1 | systemd-cat -t myscript.sh

but it doesn't work.

Update 2:

From terminal

systemd-cat ~/scripts/myscript.sh

works. But I'm still looking for a way to do this from within the script.


Solution

  • A pipe to systemd-cat is a process which needs to run concurrently with your script. Bash offers a facility for this, though it's not portable to POSIX sh.

    exec > >(systemd-cat -t myscript -p emerg) 2>&1
    

    The >(command) process substitution starts another process and returns a pseudo-filename (something like /dev/fd/63) which you can redirect into. This is basically a wrapper for the mkfifo hacks you could do if you wanted to port this to POSIX sh.