Python logging管理不同级别log打印和存储实例

Python内置模块logging管理不同级别log打印和存储,非常方便,从此告别了使用print打桩记录,我们来看下logging的魅力吧

import logging

logging.basicConfig(level = logging.DEBUG,

format = '%(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s %(message)s',

datefmt = '%a, %d %b %Y %H:%M:%S',

filename = './logcheck.log',

filemode = 'w')

###############################################################################

#define one StreamHandler, set the log mode

console = logging.StreamHandler()

console.setLevel(logging.INFO)

formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')

console.setFormatter(formatter)

logging.getLogger('').addHandler(console)

###############################################################################

filePath = r'C:\ddms.bat'

logging.error('Open file failed!')

logging.warn('sort mode disabled')

logging.debug('%s' % filePath)

logging.info('xml file generated successfully!')

运行结果:

root : ERROR Open file failed!

root : WARNING sort mode disabled

root : INFO xml file generated successfully!

总结

以上是 Python logging管理不同级别log打印和存储实例 的全部内容, 来源链接: utcz.com/z/333319.html

回到顶部