Write to custom log file from a Bash script

bash, logging, shell

Solution

`logger` logs to syslog facilities. If you want the message to go to a particular file you have to modify the syslog configuration accordingly. You could add a line like this:

local7.*   -/var/log/mycustomlog

and restart syslog. Then you can log like this:

logger -p local7.info "information message"
logger -p local7.err "error message"

and the messages will appear in the desired logfile with the correct log level.

Without making changes to the syslog configuration you could use `logger` like this:

logger -s "foo bar" 2>> /var/log/mycustomlog

Specifying `-s` or `--stderr` instructs `logger` to print the message to STDERR as well (in addition to logging it to syslog), so you could redirect STDERR to a file. However, it would be utterly pointless, because the message is already logged via syslog anyway (with the default priority `user.notice`). Note that we use here `2>>` to append standard error to the file named.

Problem

In Linux, I know how to write a simply message to the `/var/log/messages` file, in a simple shell script I created: ``` #!/bin/bash logger "have fun!" ``` I want to stop throwing messages into the default `/var/log/messages` file, and create my own. I tried this: ``` #!/bin/bash logger "have more fun" > /var/log/mycustomlog ``` It still logs to `/var/log/messages`. It did create the `/var/log/mycustomlog`, but it's empty. Anyone see what I'm missing?

Original source

Related problems