#!/bin/echo Warnning, this library must only be sourced!
# vim: set expandtab smarttab shiftwidth=4 tabstop=4:
#
# Author: tuantuan.lv <tuantuan.lv@alibaba-inc.com>
# Description: a simple log library for pet
#
# Create the log file if not exists
# $1: the log file name
function _create_logfile()
{
# FIXME: change the permission of log file
if [ ! -f "$1" ]; then
mkdir -p `dirname $1`; touch $1; chmod 666 $1
fi
}
#
# Prevent the pet log library to be sourced again, so we can protect
# the log file to be created only once.
#
function _prevent_sourced_again()
{
_petlog_sourced_="__petlog_sourced_$$__"
if [ -n "${!_petlog_sourced_}" ]; then
return
fi
eval "$_petlog_sourced_=1"
# Set the default log file path
if [ -f "$0" ]; then # Use the script name (not including the extension)
_petlog_filename="/tmp/$(basename $0 | awk -F. '{print $1}').log.`date +'%Y%m%d'`"
else # Otherwise, just using the default name
_petlog_filename="/tmp/petlog.log.`date +'%Y%m%d'`"
fi
_create_logfile "$_petlog_filename"
# The log level, we only print logs whose level less than this
_petlog_level=3 # DEBUG
# The log data format
_petlog_datefmt='%Y-%m-%d %H:%M:%S' # 2014-11-11 11:11:11
# The log line format
_petlog_fmt="[<levelname>] [<asctime>] <message>" # [DEUBG] [2014-11-11 11:11:11] a simple log
}
# Print log messages
# $1: The log level number
# $2: C-style printf format string
# $3..$N: C-style printf arguments
function _print_log()
{
local level=$1 msg="$2" fmt="${_petlog_fmt}"
local levelnames=('ERROR' 'WARNING' 'INFO' 'DEBUG')
local logcolors=('red' 'yellow' 'green' '')
# Prepare the log format strings
fmt="${fmt//<asctime>/$(date +"$_petlog_datefmt")}"
fmt="${fmt//<message>/$msg}"
fmt="${fmt//<levelname>/${levelnames[$level]}}"
# We also decide to print all the log messages to the log file
shift 2 && printf "$fmt" "$@" >> $_petlog_filename
# Only print the log whose level less than the log level we set before
if [ $level -le $_petlog_level ]; then
${logcolors[level]:-printf} "$fmt" "$@"
fi
}
#
# Make the strings to be echoed as differnt colors
#
function red() { printf "