python的logging日志模块介绍 打印日志到控制台 打印日志到文件
- 2015-06-13 15:14:00
- admin
- 原创 5102
一、打印日志到控制台
1、logging线程安全,可以放心在多线程环境下打印日志;
2、logging默认输出日志到控制台,日志级别为WARNING,等于或大于该级别的日志会输出;
3、日志级别大小关系:CRITICAL > ERROR > WARNING > INFO > DEBUG,可以自定义日志级别;
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
二、打印日志到文件
1、filemode默认为a,追加日志;
2、level默认为WARNING;
3、filename和stream同时出现,优先使用filename;
FORMAT = '%(asctime)s.%(msecs)d|%(levelname)s| - %(message)s'
DATEFMT = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(level=logging.DEBUG,
format=FORMAT, datefmt=DATEFMT, filename='app.log', filemode='w')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
三、打印日志到控制台和文件
1、basicConfig的日志级别设置对所有handler有效;
2、日志级别=MAX(basicConfig.LogLvl, handle.LogLvl)
FORMAT = '%(asctime)s.%(msecs)d|%(levelname)s| - %(message)s'
DATEFMT = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(level=logging.DEBUG, format=FORMAT, datefmt=DATEFMT)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
console.setFormatter(logging.Formatter(FORMAT, DATEFMT))
logging.getLogger('').addHandler(console)
fileLog = logging.FileHandler('app.log')
fileLog.setLevel(logging.DEBUG)
fileLog.setFormatter(logging.Formatter(FORMAT, DATEFMT))
logging.getLogger('').addHandler(fileLog)
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
四、日志文件旋转
# -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
FORMAT = '%(asctime)s.%(msecs)d|%(levelname)s| - %(message)s'
DATEFMT = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(level=logging.DEBUG, format=FORMAT, datefmt=DATEFMT)
rotateHandler = RotatingFileHandler('myapp.log', maxBytes=10*1024*1024, backupCount=5)
rotateHandler.setLevel(logging.DEBUG)
rotateHandler.setFormatter(logging.Formatter(FORMAT, DATEFMT))
logging.getLogger('').addHandler(rotateHandler)
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
五、日志模块配置文件
配置文件app.conf:
[loggers]
keys=root,errout
[logger_root]
level=DEBUG
handlers=hd01,hd02
[logger_errout]
qualname=errout
propagate=0
level=DEBUG
handlers=hd01
[handlers]
keys=hd01,hd02
[handler_hd01]
class=StreamHandler
level=DEBUG
formatter=fmt01
args=(sys.stderr,)
[handler_hd02]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=fmt01
args=('app.log', 'a', 10*1024*1024, 5)
[formatters]
keys=fmt01
[formatter_fmt01]
format=%(asctime)s.%(msecs)d|%(levelname)s| - %(message)s
datefmt=%Y-%m-%d %H:%M:%S
示例代码:
# -*- coding: utf-8 -*-
import logging
import logging.config
logging.config.fileConfig("app.conf")
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.getLogger('errout').info('to stderr')