DEV Community

Cover image for Auto-magically log all output of your script to syslog
An Rodriguez
An Rodriguez

Posted on • Originally published at Medium

Auto-magically log all output of your script to syslog

Not long ago I stumbled upon this solution to automatically send all output of a bash script to syslog.

All you have to do is add the command at the beginning of the script and all following output will be written to syslog along with the script name.

The solution uses the logger interface to syslog.

The line is

exec 1> >(logger -s -t $(basename $0)) 2>&1
Enter fullscreen mode Exit fullscreen mode

For example, say we have this executable bash script and we name it autolog.sh:

#/bin/env bash

exec 1> >(logger -s -t $(basename $0)) 2>&1

echo 'Hello World'
Enter fullscreen mode Exit fullscreen mode

If we execute it and then see syslog we get:

$ ./autolog.sh
<13>Feb 16 22:30:30 autolog.sh: Hello World

# tail /var/log/syslog
...
Feb nn nn:nn:nn ip-nnn-nn-n-nnn autolog.sh: Hello World
Enter fullscreen mode Exit fullscreen mode

I took this solution from here: http://urbanautomaton.com/blog/2014/09/09/redirecting-bash-script-output-to-syslog/, but the URL is currently broken.


Do you have any tips for logging on bash? Let me know!

Top comments (4)

Collapse
 
stevezieglerva profile image
Steve Ziegler

So why do you do that? Consolidate everything into one place?

Collapse
 
anrodriguez profile image
An Rodriguez

syslog is where everybody first looks to debug an issue.
So if your script logs there - at least its errors - then it probable its easier to find/debug/maintain.
serverfault.com/a/527293

Collapse
 
stevezieglerva profile image
Steve Ziegler

Good points. Thanks.

Collapse
 
tiennmld profile image
Tien Nguyen Minh

Awesome. Thanks you
I searched a lot to find it