Python logging 示例
介绍
- 参考
- 相关 Handler
- StreamHandler
- FileHandler
- NullHandler
- WatchedFileHandler
- BaseRotatingHandler
- RotatingFileHandler
- TimedRotatingFileHandler
- SocketHandler
- DatagramHandler
- SysLogHandler
- NTEventLogHandler
- SMTPHandler
- MemoryHandler
- HTTPHandler
- QueueHandler
- QueueListener
logging.error('xxx', exc_info=True, stack_info=True, extra={'user': 'Tom'})
- exc_info=True 将异常信息添加到日志消息中
- stack_info=True 将栈信息会被添加到日志信息中
- extra 添加额外信息
示例
demo1
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import sys
## start log
# create logger
log_level = logging.DEBUG
formatter = logging.Formatter(
fmt="%(asctime)-15s %(levelname)s %(process)d %(filename)s %(lineno)d: %(message)s",
datefmt="%a %d %b %Y %H:%M:%S")
logger = logging.getLogger(name="test")
logger.setLevel(log_level)
fh = logging.FileHandler(filename="test.log")
fh.setLevel(log_level)
fh.setFormatter(formatter)
logger.addHandler(fh)
oh = logging.StreamHandler(sys.stdout)
oh.setLevel(log_level)
oh.setFormatter(formatter)
logger.addHandler(oh)
## end log
logger.debug("debug")
logger.info("info")
logger.info("info")
demo2
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
# import logging.handlers
from logging import handlers
import datetime
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
rfh = handlers.TimedRotatingFileHandler(
'all.log', when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
rfh.setFormatter(
logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
fh = logging.FileHandler('error.log')
fh.setLevel(logging.ERROR)
fh.setFormatter(
logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s"))
logger.addHandler(rfh)
logger.addHandler(fh)
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')
demo3
根据日志级别写入不同的文件
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
# import logging.handlers
from logging import handlers
import datetime
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
rfh = handlers.TimedRotatingFileHandler(
'all.log', when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
rfh.setFormatter(
logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
fh = logging.FileHandler('error.log')
fh.setLevel(logging.ERROR)
fh.setFormatter(
logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s"))
logger.addHandler(rfh)
logger.addHandler(fh)
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')