logging in bash

This function will only log an entry when the script is in debug mode. This is a much usefull way then changing a variable inside the script itself:

log(){
    : ${DEBUG:=0}
    : ${LOG_PATH:=/var/log/logfile.log}
    [[ $DEBUG == "1" ]] && echo $(date +%Y-%m-%d:%S) $1 >> $LOG_PATH
}

When you need it inside the script, just add:

log "log message" 

To run in debug mode call your script with DEBUG=1 before the path to your script. For example, if your script is in /usr/bin/myScript , call it like this:

DEBUG=1 /usr/bin/myScript

If you want to temporarily change the location of the log file you can call the script like this:

DEBUG=1 LOG_PATH=/tmp/temp.log /usr/bin/myScript

Alternatively, if you want to write directly into the system log (/var/log/messages) you can use a utility named logger:

log(){
    : ${DEBUG:=0}
    [[ $DEBUG == "1" ]] && logger $1 -t "[$(basename "$0")]"
}

This will write the message with a tag of the script name for easy grepping the systemlog file. You can change the loggging style. Checkout man logger for more info.

Remember: if you have your own custom log files, you need to make sure they do not grow until they take the whole disk space. It is s advised to create a logrotate rule for them.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s