Logging to syslog from Your Script

Problem

You’d like your script to be able to log to syslog.

Solution

Use logger, Netcat, or bash’s built-in network redirection features.

logger is installed by default on most systems and is an easy way to send messages to the local syslog service. However, it does not send syslog to remote hosts by itself. If you need to do that, you can use bash or Netcat.

$ logger -p local0.notice -t ${0##*/}[$$] test message

Netcat is known as the “TCP/IP Swiss Army knife” and is usually not installed by default. It may also be prohibited as a hacking tool by some security policies, though bash’s net-redirection features do pretty much the same thing. See the discussion in Using bash Net-Redirection for details on the <133>${0##*/}[$$] part.

# Netcat
$ echo "<133>${0##*/}[$$]: Test syslog message from Netcat" | nc -w1 -u loghost 514

# bash
$ echo "<133>${0##*/}[$$]: Test syslog message from bash" \
  > /dev/udp/loghost.example.com/514

Discussion

logger and Netcat have many more features than we include here. See the respective manpages for details.

See Also

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.