Is there something like log4j for bash?

Is there something like log4j for bash script? I would like to be able to treat errors differently based on their severity. For example, log4j allows me to differentiate between errors, info, debug, etc. Is there a way I can do that for bash?

I know, I can just write a function , that write to log as the following example:

LOG ()  { 
           echo `date` $* >> /var/log/my_log.log 

But actually I want to know if something like log4j is relevant for bash

in order to get the ability for – error level and etc

Asked By: maihabunash


Most systems have the logger utility, which knows how to talk to syslogd. It allows you to set log level (severity), facility name, specify the log file to write to, send to syslogd on a remote host, write messages to STDERR as well as to the system log.

The logging semantics are not quite the same as those provided by tools like log4j, but by combining the facility.level settings with message tags, you can achieve something very close.


NOTE: These examples use the FreeBSD version of logger. Your system may have different options, so read your local documentation!

logger -p -f /var/log/messages -t MY_LOG_TAG "something interesting happened"

This will send the message to be logged in /var/log/messages with a severity of info, in the local3 facility. It includes a tag (-t MY_LOG_TAG), which is included in each line. Tags are useful for extracting log entries with grep, awk, etc.

logger -h loghost -p mail.crit -s -f /var/log/mail "an unrecoverable error has occurred"

This one sends the message with severity crit in the mail facility to the remote machine loghost, to be logged in /var/log/mail. The -s causes the message to be printed on the the script’s STDERR as well as sending it to be logged.

Answered By: D_Bye

There’s good amount of detail on logging for shell scripts via global
varaibles of shell. We can emulate the similar kind of logging in shell

The post has details on introdducing log levels like INFO , DEBUG, ERROR.
Tracing details like script entry, script exit, function entry, function exit.

Sample Log:

enter image description here

Answered By: Piyush Chordia

You may want to take a look at my logging implementation on GitHub:

It supports five log levels (ERROR, WARN, INFO, DEBUG, and VERBOSE) as well as multiple loggers.

Answered By: codeforester
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.