python 关于Python logging的杂记

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 关于Python logging的杂记相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
参考链接:

1. https://docs.python.org/3/library/logging.html#logrecord-objects
2. http://stackoverflow.com/questions/8702230/python-catch-any-exception-and-print-or-log-traceback-with-variable-values
"""

import sys
import logging
import traceback
import logging.config

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)s %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        }
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': "app.log",
            'formatter': 'verbose',
        },
        'error_file': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': 'app.err',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'error': {
            'handlers': ['error_file'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

logging.config.dictConfig(LOGGING)
elog = logging.getLogger('error')

def handleException(etype, value, tb):
    elog.error(''.join(traceback.format_exception(etype, value, tb)))

sys.excepthook = handleException

elog.error("HELLO, WORLD")

1 / 0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-


"""
Python logging filters examples.

参考链接:

1. http://stackoverflow.com/questions/21455515/install-filter-on-logging-level-in-python-using-dictconfig
2. https://docs.python.org/3/library/logging.html#logrecord-objects

"""

import logging
import logging.config

class MyFilter(logging.Filter):
    def __init__(self, param=None):
        self.param = param

    def filter(self, record):
        if self.param is None:
            allow = True
        else:
            allow = self.param not in record.msg
        if allow:
            record.msg = 'changed: ' + record.msg
        return allow

logging.config.dictConfig({
    'version': 1,
    'filters': {
        'MyFilter': {
            '()': MyFilter,
            'param': 'noshow'
        }
    },
    'formatters': {
        'console': {
            'format': '%(asctime)s [%(name)s]: %(message)s'
        }
    },
    'handlers': {
        'consoleHandler': {
            'class': 'logging.StreamHandler',
            'formatter': 'console',
            'filters': ['MyFilter'],
            'stream': 'ext://sys.stdout',
        }
    },
    'loggers': {
        '': {
            'handlers': ['consoleHandler'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'home': {
            'level': 'INFO',
            # 注意如果这里 propagate 设置为False,
            # michael logger的记录日志事件也传递不上去了
            'propagate': True,
        },
        'home.michael': {
            'level': 'DEBUG',
            'propagate': True,
        },
    }
})

home = logging.getLogger('home')
michael = logging.getLogger('home.michael')

home.info('A message from home logger - noshow')
michael.debug('A debug messge from home.michael logger')

以上是关于python 关于Python logging的杂记的主要内容,如果未能解决你的问题,请参考以下文章

python 关于Python logging的杂记

关于python logging的 NOTSET 级别

暂未分类的杂题

关于python logging模块读文档的几个心得

2018/06/09,临近离校的杂想

关于 Linux 下后台执行 Python 脚本的缓冲问题