Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/bas080/bash-logger

Bash logging utility
https://github.com/bas080/bash-logger

Last synced: 21 days ago
JSON representation

Bash logging utility

Awesome Lists containing this project

README

        

# Bash Logger

> Simple log functionality for bash

- Writes everything to /dev/stderr.
- STDIN support.
- Easy to setup.

## Usage

Simply source the script and use the functions it defines.

```bash bash 2>&1
source ./bash-logger; log_error "error"
```
```
2022-10-21T10:57:49+02:00[error] error
```

An important part of the logger utility is the stdin support.

```bash bash 2>&1
source ./bash-logger; echo 'warn' | log_warn
```
```
2022-10-21T10:57:49+02:00[warn] warn
```

## Functions

Let's checkout all the functions that exist.

```bash bash 2>&1
grep '^function ' ./bash-logger
```
```
function log ()
function log_date ()
function log_error() { log 1 "${1:-}"; }
function log_warn() { log 2 "${1:-}"; }
function log_info() { log 3 "${1:-}"; }
function log_debug() { log 4 "${1:-}"; }
function log_trace() { log 5 "${1:-}"; }
```

## Variables

```bash bash 2>&1
grep '^LOGGER_[A-Z]*=' ./bash-logger
```
```
LOGGER_FILE="${LOGGER_FILE:-/dev/null}";
LOGGER_LEVEL="${LOGGER_LEVEL:-3}";
LOGGER_TEMPLATE="${LOGGER_TEMPLATE:-%s[%s] %b\n}";
LOGGER_SILENT="${LOGGER_SILENT:-}"
```

You can write the log to a file by defining the `LOGGER_FILE`.

```bash bash 2>&1
source ./bash-logger; echo 'warn' | LOGGER_FILE="./bash-logger.log" log_info "info"
cat ./bash-logger.log
rm ./bash-logger.log # Cleaning up
```
```
2022-10-21T10:57:49+02:00[info] info
2022-10-21T10:57:49+02:00[info] info
```

How to use the `LOGGER_LEVEL`?

```bash bash 2>&1
source ./bash-logger; log_trace "trace"
```

Notice that trace is not printed. By default the `LOGGER_LEVEL` is set to
info(3) by default.

```bash bash 2>&1
source ./bash-logger; LOGGER_LEVEL=5 log_trace "trace"
```
```
2022-10-21T10:57:49+02:00[trace] trace
```

You can change the `LOGGER_TEMPLATE` if desired. The template is a printf
templates. See `man printf` for more information.

By default the `LOGGER_TEMPLATE` is the following.

```bash bash 2>&1
source ./bash-logger; echo "$LOGGER_TEMPLATE";
source ./bash-logger; printf "$LOGGER_TEMPLATE" '' '' ''
```
```
%s[%s] %b\n
[]
```

## Define your own date.

You can overwrite the date format by simply defining your own log_date function.

```bash bash 2>&1
source ./bash-logger;

# Make sure to define your function after sourcing bash-logger.

log_date() {
echo 'my own date'
}

log_error 'important'
```
```
my own date[error] important
```

## License

[GPLv3](./LICENSE.md)