python日志输出(二)-logging输出

1.常用参数

  • Level
    设置了输出 level,系统便只会输出 level 数值大于或等于该 level 的的日志结果,例如我们设置了输出日志 level 为 INFO,那么输出级别大于等于 INFO 的日志,如 WARNING、ERROR 等,DEBUG 和 NOSET 级别的不会输出。
等级 数值
CRITICAL 50
FATAL 50
ERROR 40
WARNING 30
WARN 30
INFO 20
DEBUG 10
NOTSET 0
  • Formatter
格式 意义
%(levelno)s 打印日志级别的数值
%(levelname)s 打印日志级别的名称。
%(filename)s 打印当前执行程序名
%(pathname)s 打印当前执行程序的路径,其实就是sys.argv[0]。
%(funcName)s 打印日志的当前函数
%(lineno)d 打印日志的当前行号
%(asctime)s 打印日志的时间
%(thread)d 打印线程ID
%(threadName)s 打印线程名称
%(process)d 打印进程ID
%(processName)s 打印进程名称
%(module) 打印模块名称
%(message)s 打印日志信息
2.Handler模式
  • libs\lib\log_test.py
import logging logger = logging.getLogger('test.log_test') def run(): logger.info('Core Info') logger.debug('Core Debug') logger.error('Core Error')

  • test.py
import logging from logging.handlers import HTTPHandler import sys import libs.lib.log_test as log_test #initial logger logger = logging.getLogger("test") logger.setLevel(level=logging.DEBUG) # StreamHandler stream_handler = logging.StreamHandler(sys.stdout) stream_handler.setLevel(level=logging.DEBUG) logger.addHandler(stream_handler) # FileHandler file_handler = logging.FileHandler('output.log') file_handler.setLevel(level=logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) logger.addHandler(file_handler) # HTTPHandler # http_handler = HTTPHandler(host='localhost:8001', url='log', method='POST') # logger.addHandler(http_handler) # Log logger.info('This is a log info') logger.debug('Debugging') logger.warning('Warning exists') logger.info('Finish') #catch exception try: result = 10 / 0 except Exception: logger.error('Faild to get result', exc_info=True) logger.exception('Faild to get result', exc_info=True) log_test.run()

3. Config模式
  • libs\lib\config.yaml
version: 1 formatters: brief: format: "%(asctime)s - %(message)s" simple: format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" handlers: console: class : logging.StreamHandler formatter: brief level: INFO stream: ext://sys.stdout file: class : logging.FileHandler formatter: simple level: DEBUG filename: debug.log error: class: logging.handlers.RotatingFileHandler level: ERROR formatter: simple filename: error.log maxBytes: 10485760 backupCount: 20 encoding: utf8 loggers: main.core: level: DEBUG handlers: [console, file, error] root: level: DEBUG handlers: [console]

  • libs\lib\log_test.py
import logging logger = logging.getLogger('test.log_test') def run(): logger.info('Core Info') logger.debug('Core Debug') logger.error('Core Error')

  • test.py
import logging import libs.lib.log_test as log_test import yaml import logging.config import osdef setup_logging(default_path='config.yaml', default_level=logging.INFO): path = default_path if os.path.exists(path): with open(path, 'r', encoding='utf-8') as f: config = yaml.load(f) logging.config.dictConfig(config) else: logging.basicConfig(level=default_level)def log(): logging.debug('Start') logging.info('Exec') logging.info('Finished')if __name__ == '__main__': yaml_path = 'E:\python_sample\libs\lib\config.yaml' setup_logging(yaml_path) log() log_test.run()

    推荐阅读