Bash 日志配置
使用输出重定向实现日志记录
使用 echo
命令加输出重定向实现日志记录:
1echo "This is a line." >> shell.log
2echo "This is another line." >> shell.log
自定义函数实现日志记录
简单日志记录函数
1#!/bin/bash
2
3function log() {
4 msg=$1
5 echo $msg >> shell.log
6}
7
8log "This is a line."
9log "This is another line."
日志分级
1#!/bin/bash
2
3function info() {
4 echo -e "\033[32m$*\033[0m"
5}
6
7function warning() {
8 echo -e "\033[33m$*\033[0m"
9}
10
11function error() {
12 echo -e "\033[31m$*\033[0m"
13}
14
15function logging() {
16 level=$1
17 shift
18 case $level in
19 "info")
20 info "$*";;
21 "warning")
22 warning "$*";;
23 "error")
24 error "$*";;
25 *)
26 echo "$*";;
27 esac
28}
29
30# Test
31logging info "This is an info message."
32logging warning "This is a warning message."
33logging error "This is an error message."
日志效果如下:
日志格式化
1#!/bin/bash
2
3function info() {
4 log="$(date '+%Y-%m-%d %H:%M:%S') - INFO - $*"
5 echo -e "\033[32m${log}\033[0m"
6 echo "${log}" >> shell.log
7}
8
9function warning() {
10 log="$(date '+%Y-%m-%d %H:%M:%S') - WARNING - $*"
11 echo -e "\033[33m${log}\033[0m"
12 echo "${log}" >> shell.log
13}
14
15function error() {
16 log="$(date '+%Y-%m-%d %H:%M:%S') - ERROR - $*"
17 echo -e "\033[31m${log}\033[0m"
18 echo "${log}" >> shell.log
19}
20
21function logging() {
22 level=$1
23 shift
24 case $level in
25 "info")
26 info "$*";;
27 "warning")
28 warning "$*";;
29 "error")
30 error "$*";;
31 *)
32 echo "$*";;
33 esac
34}
35
36# Test
37logging info "This is an info message."
38logging warning "This is a warning message."
39logging error "This is an error message."
日志效果如下: