LoginSignup
2
4

More than 1 year has passed since last update.

Pythonのloggingでログ出力先ごとに例外スタックトレースの要否を設定する

Last updated at Posted at 2021-06-01

概要

Pythonのlogging.Logger.exceptionを使用する際、ログ出力先(Handler)ごとに例外スタックトレースを出力するかどうかを設定したい。JavaのLog4jなら%throwableで設定できるが、loggingには同様のフォーマットがなく(標準Formatterを使う限り)必ず出力されることになる。

したがって、個別に設定するためには例外スタックトレースを出力しない独自Formatterを定義する必要がある。

実装例

ログファイルには例外スタックトレースを出力し、コンソールには出力しない実装例。

sample.py
from logging import getLogger, config, Formatter

class NoExceptionFomatter(Formatter):
    """例外スタックトレースを出力しないFormatter"""
    def format(self, record):
        record.message = record.getMessage()
        if self.usesTime():
            record.asctime = self.formatTime(record, self.datefmt)
        return self.formatMessage(record)

# ログ設定
config.dictConfig({
    'version': 1,
    'formatters': {
        'standard': {
            'format': '%(asctime)s %(name)s %(levelname)s %(message)s'
        },
        'custom': {
            '()': NoExceptionFomatter,
            'format': '%(asctime)s %(name)s %(levelname)s %(message)s'
        }
    },
    'handlers': {
        'file': {
            'class': 'logging.FileHandler',
            'filename': 'sample.log',
            'formatter': 'standard'
        },
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'custom'
        }
    },
    'loggers': {
        'sample': {
            'level': 'INFO',
            'handlers': ['file', 'console']
        }
    }
})

# ロガー
logger = getLogger('sample')

# ログ出力
try:
    1 / 0
except:
    logger.exception('exception')

標準Formatterを継承して独自Formatterを定義し、formatメソッドをオーバライドする。
オーバライド後の処理は標準Formatterのformatメソッドから例外スタックトレース付与を省略したもの(上記の実装例ではexc_infoだけでなくstack_infoも省略)

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4