您的位置:首页 > 编程语言 > Python开发

python logging 简单使用总结

2015-01-10 23:38 471 查看
logging模块简单使用:

----

1. logging.basicConfig简单设置 filename format datefmt level(默认为DEBUG)

eg.

logging.basicConfig(format='%(asctime)s %(levelname)s [%(filename)s:%(lineno)s]: %(message)s', level=logging.DEBUG)

2. 如果要写入文件 上述参数中加入 filename='test.log'

3. 打印日志: logging.debug() logging.info() logging.warning() ...

4. output log message both to file&&terminal

* python2中logging 输出到file和stdout是互斥的。 需要用到logger=logging.getLogger() 对象,然后为其addHandler两个handler

filename='./test.log'

level=logging.DEBUG

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

s = logging.StreamHandler() #new stdout Handler

s.setLevel(level)

s.setFormatter(logging.Formatter(format))

logging.basicConfig(filename=filename, format=format, level=level) #set default Handle

logging.getLogger().addHandler(s) #get the default(root) Logger and add stdout Handler

* python3中很简单

targets = logging.StreamHandler(sys.stdout), logging.FileHandler('test.log')

logging.basicConfig(format='%(message)s', level=logging.INFO, handlers=targets)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: