#!/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 "\033[1;31m$(echo "$1" | sed -r 's/(\\n)?$/\\033[0m\1/')" "${@:2}"; }
function yellow() { printf "\033[1;33m$(echo "$1" | sed -r 's/(\\n)?$/\\033[0m\1/')" "${@:2}"; }
function green() { printf "\033[1;32m$(echo "$1" | sed -r 's/(\\n)?$/\\033[0m\1/')" "${@:2}"; }
function blue() { printf "\033[1;34m$(echo "$1" | sed -r 's/(\\n)?$/\\033[0m\1/')" "${@:2}"; }
function cyan() { printf "\033[1;36m$(echo "$1" | sed -r 's/(\\n)?$/\\033[0m\1/')" "${@:2}"; }
function purple() { printf "\033[1;35m$(echo "$1" | sed -r 's/(\\n)?$/\\033[0m\1/')" "${@:2}"; } #
# Log print functions, such as debug_msg, info_msg... etc.
#
# Define the log level constants, just for convenience
LOG_QUIET=-1 LOG_ERROR=0 LOG_WARNING=1 LOG_INFO=2 LOG_DEBUG=3 function debug_msg() { _print_log $LOG_DEBUG "$1" "${@:2}"; }
function info_msg() { _print_log $LOG_INFO "$1" "${@:2}"; }
function warn_msg() { _print_log $LOG_WARNING "$1" "${@:2}"; }
function error_msg() { _print_log $LOG_ERROR "$1" "${@:2}"; return 1; }
function die_msg() { error_msg "$@"; exit 1; }
function exit_msg() { die_msg "$@"; } # should be deprecated, use die_msg instead
function warning_msg() { warn_msg "$@"; } # the same as warn_msg #
# Customize the log functions
#
# Set the default log file
# $1: the log filename
function set_logfile()
{
if [ -z "$1" ]; then
die_msg "the log filename is empty\n"
fi _petlog_filename="$1"
_create_logfile "$_petlog_filename"
} # Get the log filename
function get_logfile() { echo "$_petlog_filename"; } # Set the default log level
# $1: level name or level number
function set_loglevel()
{
if echo "$1" | grep -qE "^(-1|0|1|2|3)$"; then
_petlog_level="$1"
elif echo "$1" | grep -qE '^LOG_(QUIET|DEBUG|INFO|ERROR|WARNING)$'; then
_petlog_level="${!1}"
else
die_msg "the log level is not valid, please check\n"
fi
} # Set log format
function set_logfmt()
{
if [ -z "$1" ]; then
die_msg "the log format is empty, please check\n"
fi _petlog_fmt="$1"
} # Set the log date format
# $1: the log date format, see `man data`
function set_logdatefmt()
{
if [ -z "$1" ]; then
die_msg "the log data format is empty, please check\n"
fi _petlog_datefmt="$1"
} _prevent_sourced_again # Yeah, prevent to be sourced again
#!/bin/bash
. ./log.sh echo "1. use default log settings"
echo debug_msg "hello,world\n"
info_msg 'hello,world\n'
warn_msg 'hello,world\n'
warning_msg 'hello,world\n'
error_msg 'hello,world\n'
g
echo
echo "2. set loglevel to $LOG_INFO"
echo set_loglevel $LOG_INFO
debug_msg "hello,world\n"
info_msg 'hello,world\n'
warn_msg 'hello,world\n'
error_msg 'hello,world\n' echo
echo "3. set log fmt to [<asctime> - <levelname>] <message>"
echo set_logfmt "[<asctime> - <levelname>] <message>"
info_msg 'hello,%s\n' world
warn_msg 'hello,%s\n' pet echo
echo "4. set date fmt to %Y/%m/%d %H:%M:%S"
echo set_logdatefmt "%Y/%m/%d %H:%M:%S"
info_msg 'hello,world\n'
warn_msg 'hello,world\n' echo
echo '5. use colorful print'
echo red "hello,world\n"
green "hello,world\n"
yellow "hello,world\n"
cyan "hello,world\n"
purple "hello,world\n"
blue "hello,world\n" echo
echo '6. exit script'
echo
die_msg "exit script\n"

log.sh的更多相关文章

  1. Shell Scipt 命令行带参数,输出log

    命令行带参数,以及字符串参数放到ssh命令里可以这么放: #!/bin/bash        这行保证运行bash可以这样: ./data.sh if [ $# != 4 ]; then echo ...

  2. linux 使用sh@d0ws0cks server

    [root@linux-node1 ~]# cat /etc/shadowsocks.json { "server":"x.x.x.x", , "lo ...

  3. Code HighLight

    #!/bin/sh BEG=`date --date '-7 days' +%Y%m%d` END=`date --date '-1 days' +%Y%m%d` #BEG='20140509' #E ...

  4. xargs的原理剖析及用法详解

    转载请注明出处:http://www.cnblogs.com/f-ck-need-u/p/5925923.html 学习这个xargs花了很长时间,在网上翻了很久也查了很多书关于xargs的介绍,都只 ...

  5. lsof在运维中的应用

    场景一:文件系统使用率很高,但是找不到具体哪个文件占用了空间 原因:在unix系统中,如果有两个进程同时使用一个文件,如果其中一个进程删除了这个文件,但是这个文件此刻不会正真被释放,一直要等待引用它的 ...

  6. build.xml配置编译打包过程(转)

    工程目录如下,使用eclipse中的ant对此工程进行编译打包: MonServer | --------src |            |--------com |            |--- ...

  7. Linux Commands intro1

    $((expression)) echo $(2+2) :wrong echo $((2+2))  : right echo Front-{A,B,C}-Back Front-A-Back Front ...

  8. 【Linux】/dev/null 2>&1 详解

     今天一个朋友突然在自己的维护的Linux中, /var/spool/cron/root 中看到了以下的内容: 30 19 * * * /usr/bin/**dcon.sh > /dev/nul ...

  9. crontab 日志备份定时任务

    -l选项,查看当前用户的所有定时任务: [xiluhua@vm-xiluhua][/home]$ crontab -l * * * * * /home/xiluhua/shell_script/log ...

随机推荐

  1. 如何为Myeclipse手工添加dtd支持

    一.引言 在MyEclipse中开发三大框架的项目时候经常会写一些配置的xml文件,例如:Struts2的struts.xml和Hibernate的hibernate.cfg.xml.Spring的a ...

  2. Android中ListView的优化

    第一种方法 重用了convertView,很大程度上的减少了内存的消耗.通过判断convertView是否为null,是的话就需要产生一个视图出来,然后给这个视图数据,最后将这个视图返回给底层,呈献给 ...

  3. eclipse-android-activity_main/fragment_main文件处理

    android新建工程后,在res/layout/下有两个文件,之前用studio的时候貌似没有,只有一个文件,然后再测试Activity切换的时候,一直在纠结这个问题,下面是解决方法: 1)将fra ...

  4. file控件change事件触发问题

    最近,项目中需要用到一个图片上传的功能,我用的file控件来选取图片文件,然后利用js读取文件来预览图片,最后再根据用户的操作来决定是否上传文件. 其中碰到了一个奇怪的问题:在选取完第一张图片,并上传 ...

  5. python 下的数据结构与算法---8:哈希一下【dict与set的实现】

    少年,不知道你好记不记得第三篇文章讲python内建数据结构的方法及其时间复杂度时里面关于dict与set的时间复杂度[为何访问元素为O(1)]原理我说后面讲吗?其实就是这篇文章讲啦. 目录: 一:H ...

  6. 前端CSS兼容的一些思路

    半夜睡不着觉,起来写第一博. 近段时间,公司要给一个网站产品增加一个换色功能,安排我负责该事项. 之前参与过一些定制项目,是基于该产品的二次开发,说实话里面的前端结构很混乱.所以第一步就是将html前 ...

  7. Linq中字段数据类型转换问题(Linq to entity,LINQ to Entities 不识别方法"System.String ToString()"问题解决)

    1.在工作中碰到这样一个问题: 使用linq时,需要查询两个表,在这两张表中关联字段分别是int,和varchar()也就是string,在linq中对这两个字段进行关联, 如果强制类型转换两个不同类 ...

  8. java转换流

    转换流是把字节流转换成字符流,比如往一个文件中写内容,原本是一个字节一个字节的写,转换为字符流后,我们可以一个字符串,一个字符串的写,书写中文很方便 转换流class: OutputStreamWri ...

  9. libusb简介

    概述 libusb是一个C库,它提供了通用的访问USB设备. 它的目的是供开发人员使用方便的生产与USB通信硬件的应用程序. 可移植的: 使用一个跨平台API,它提供了访问USB设备在Linux上,O ...

  10. R2:获取一个event_base

    原文链接:http://www.wangafu.net/~nickm/libevent-book/Ref2_eventbase.html 创建一个event_base 在你使用任何有意思的Libeve ...