日志不管对于开发或者运维都是一项非常重要的东西,它可以用来排错,解决故障,统计分析等。
本文介绍python中的日志库的用法。
导入日志库:import logging
日志库的主要有以下方法:
获取日志名,比如
logging.getLogger(__name__)
定义Handler,比如
logging.FileHandler('/var/log/messages')
设置级别,比如
fh.setLevel(logging.DEBUG)
定义格式,比如
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
打印日志,比如
LOG.error("python logging test!!")
实例1
下面给出一段脚本用来输出日志到/var/log/messages和屏幕。
import logging LOG = logging.getLogger(__name__) LOG.setLevel(logging.ERROR) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh = logging.FileHandler('/var/log/messages') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) LOG.addHandler(fh) ch = logging.StreamHandler() ch.setLevel(logging.ERROR) ch.setFormatter(formatter) LOG.addHandler(ch) LOG.error("python logging test!!")
运行下,你会发现/var/log/messages和屏幕上都会有类似“2015-06-28 07:41:41,527 - test - ERROR - python logging test!!”。
实例2
如果只是记录日志到一个文件或屏幕,可以采用简单的方法:logging.basicConfig()
import logging
logging.basicConfig(filename='example.log', level=logging.DEBUG)
logging.error("this is a error test")
实例3
下面介绍需要记录日志到不同文件的方法,这时就不能采用logging.basicConfig()了。
有两个文件,一个是main.py,一个是logger.py ,
输出到不同的日志文件需要获取不同的日志对象:logging.getLogger()
cat main.py
#!/usr/bin/env python
import logging
from logger import logger
list = ['test1', 'test2']
msg1 = "This is a testing !"
msg2 = "This is the second testing !"
def set_logger(logger_name, log_file, level=logging.INFO):
#logging.basicConfig(filename=name, level=logging.DEBUG, format='%(asctime)s %(name)s %(message)s')
l = logging.getLogger(logger_name)
formatter = logging.Formatter('%(asctime)s : %(message)s')
fileHandler = logging.FileHandler(log_file, mode='w')
fileHandler.setFormatter(formatter)
#streamHandler = logging.StreamHandler()
#streamHandler.setFormatter(formatter)
l.setLevel(level)
l.addHandler(fileHandler)
#l.addHandler(streamHandler)
for logger_name in list:
log_file = logger_name
set_logger(logger_name, log_file, level=logging.INFO)
logger(logger_name, msg1)
logger(logger_name, msg2)
cat logger.py
#!/usr/bin/env python
import logging
import os
import getpass
def log_flock(runner):
if runner is not None:
try:
fcntl.lockf(runner.output_lockfile, fcntl.LOCK_EX)
except OSError:
# already got closed?
pass
else:
pass
def log_unflock(runner):
if runner is not None:
try:
fcntl.lockf(runner.output_lockfile, fcntl.LOCK_UN)
except OSError:
# already got closed?
pass
else:
pass
def logger(logger_name, msg, flag=None, runner=None):
log_flock(runner)
mypid = str(os.getpid())
user = getpass.getuser()
log = logging.getLogger(logger_name)
if flag == 'red':
log.error(msg)
else:
log.info(msg)
log_unflock(runner)