Robottinosino
Robottinosino

Reputation: 10882

Bash logging including line number

I am used to SLF4J in Java and logging in Python where I can have function names and line numbers as fields of my output format.

Emphasis on: line number

Can I get a similar thing in Bash?

Objective: build a log_error generic function to call from my (huge) script, outputting severity level of error source, function name and line number.

Intended usage:

log_error "INFO: my info" ... # called from within my_function at line 20

Intended output:

[INFO] my_function@20 my info

Is such a thing possible at all?

Upvotes: 1

Views: 3139

Answers (3)

bearzyj
bearzyj

Reputation: 1721

Hope below example with shopt -s expand_aliases and alias could help:

try.sh

#! /usr/bin/env bash

shopt -s expand_aliases

# =============================================================
# Define the logger
# =============================================================
alias logger='logger_function [${BASH_SOURCE##*/}] [$FUNCNAME] [$LINENO] '

logger_function()
{
    echo $@
}

# =============================================================
# Use the logger
# =============================================================
my_function()
{
    logger "hello world!"
}

my_function

Test result in: GNU bash, version 3.2.57(1)-release

$ ./try.sh
[try.sh] [my_function] [20] hello world!

Considering the question is emphasizing on: line number, so in this example, the exactly same input and output of the question are not used.

But to make it more informative, the logging utility definition is added with:

  • $BASH_SOURCE
  • $FUNCNAME
  • $LINENO

So, it can print the file name, function name and line number.

Regarding to alias usage here, it looks like but isn't really comparable to a C macro according to: https://tldp.org/LDP/abs/html/aliases.html

Upvotes: 4

codeforester
codeforester

Reputation: 42999

You are better off using the BASH_LINENO array. Here is the extract from Bash Manual:

BASH_LINENO An array variable whose members are the line numbers in source files where each corresponding member of FUNCNAME was invoked. ${BASH_LINENO[$i]} is the line number in the source file (${BASH_SOURCE[$i+1]}) where ${FUNCNAME[$i]} was called (or ${BASH_LINENO[$i-1]} if referenced within another shell function). Use LINENO to obtain the current line number.

Here is a comprehensive logging implementation for Bash:

https://github.com/codeforester/base/blob/master/lib/stdlib.sh

Upvotes: 1

StarPinkER
StarPinkER

Reputation: 14271

Use $LINENO: Each time this parameter is referenced, the shell substitutes a decimal number representing the current sequential line number (starting with 1) within a script or function.

Upvotes: 2

Related Questions