Simple logging in Bash scripts

I couldn’t find much mention of logging utilities for Linux shell scripting (namely Bash), so I wrote my own fairly quickly. I wanted several functions for various levels of logging (info, debug, warning, errors, etc), and a way to adjust what levels can be displayed. I followed the fairly standard convention of using numeric values for these levels and setting a “verbosity” level. If you know of an existing solution for Bash, let me know in the comments. Anyway, here’s the main idea:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
exec 3>&2 # logging stream (file descriptor 3) defaults to STDERR
verbosity=2 # default to show warnings
silent_lvl=0
err_lvl=1
wrn_lvl=2
inf_lvl=3
dbg_lvl=4

notify() { log $silent_lvl "NOTE: $1"; } # Always prints
error() { log $err_lvl "ERROR: $1"; }
warn() { log $wrn_lvl "WARNING: $1"; }
inf() { log $inf_lvl "INFO: $1"; } # "info" is already a command
debug() { log $dbg_lvl "DEBUG: $1"; }
log() {
    if [ $verbosity -ge $1 ]; then
        # Expand escaped characters, wrap at 70 chars, indent wrapped lines
        echo -e "$2" | fold -w70 -s | sed '2~1s/^/  /' >&3
    fi
}

I added line wrapping and indenting so users don’t have to manually put in line-breaks to get nicer looking outputs, but there is the drawback that it makes the output harder to grep. Perhaps I should add an option to disable the line wrapping.

Here is a longer example with some simple option parsing (apologies for using getopt; I’m currently looking for a better solution).

This entry was posted in Linux, Software and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. sumitha nandan
    Posted 2011.11.12 at 04:15 | Permalink

    i am an M Tech student and very much interested in Natural Language Processing, but need some guidance from person like you. Hope you will definitely me.

    Thanks

  2. goodmami
    Posted 2011.11.12 at 11:16 | Permalink

    Sure, what do you need guidance with? And what school is M Tech?

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>