import logging
def _init_logging(logfile, debug=False):
if debug:
level = logging.DEBUG
else:
level = logging.INFO
logging.basicConfig(level=level, format='%(asctime)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S', filename=logfile, filemode='w')
if debug:
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
if __name__ == "__main__":
import os
debug = os.environ.get('DEBUG') and True or False
_init_logging('my.log', debug=debug)
logging.info('start')
logging.info('end')
这样程序就会知道检查环境变量DEBUG,往合适的地方打印信息了。调试程序时执行方法:
$ DEBUG=1 ./my.py
2007-10-22 17:30:59,917 INFO start
2007-10-22 17:31:02,027 INFO end
最近还写了一些perl代码,和上面差不多功能的perl代码也贴出来:
use strict;
use Log::Log4perl qw(:easy);
my $log_file = "/tmp/my.log";
if (exists $ENV{DEBUG} && $ENV{DEBUG}) {
Log::Log4perl->easy_init(
{file => ">> " . log_file, level => $DEBUG},
{file => "STDOUT", level => $DEBUG},
);
} else {
Log::Log4perl->easy_init(
{file => ">> " . $log_file, level => $DEBUG},
);
}
INFO("start...");
这里用到log4perl模块,需要提前安装:
sudo perl -MCPAN -e'install Log::Log4perl'
虽然适应了一段时间,但perl满眼$@%这些助记符,还是很阻碍阅读和思维连贯,不习惯。
没有评论:
发表评论