LoginSignup
7
5

More than 5 years have passed since last update.

FlaskでdictConfigを使ったloggingメモ

Last updated at Posted at 2018-09-04

PythonのFlaskでdictConfigを使ったlogging設定備忘録です。

1. ソース

app.py
#!/usr/bin/env python3
from flask import Flask
from logging.config import dictConfig

dictConfig({
    'version': 1,
    'formatters': {
        'file': {
            'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
        }
    },
    'handlers': {
        'file': {
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'formatter': 'file',
            'filename': './log/test.log',
            'backupCount': 3,
            'when': 'D',
        }
    },
    'root': {
        'level': 'DEBUG',
        'handlers': ['file']
    }
})

app = Flask(__name__)

@app.route('/')
def hello():
    app.logger.debug('debug')
    app.logger.info('info')
    app.logger.warn('warn')
    app.logger.error('error')
    app.logger.critical('critical')
    return 'hello'

if __name__ == "__main__":
    app.run(host='0.0.0.0')

2. dictConfig説明

項目 説明
version スキーマのバージョンで現在は 1 しか有効ではない
formatters ログのフォーマットを設定する
formatters/file ログフォーマットの定義名を file と設定している(任意)
formatters/file/format file のログフォーマットを指定
handlers ハンドラを設定する
handlers/file ハンドラの定義名を file と設定している(任意)
handlers/class ハンドラで使用するモジュールを指定
handlers/formatter class で設定したモジュールの引数
handlers/filename 同上(ログ出力先)
handlers/backupCount 同上(ローテート数)
handlers/when 同上(ローテートタイミング、ここではdaily)
root ルートロガーの設定
root/level ログに記録するロガーレベルを設定(ここではDEBUG以上のものは記録)
root/handlers 使用するハンドラを設定

3. 記録されるログ例

[2018-09-04 21:50:37,492] DEBUG in app: debug
[2018-09-04 21:50:37,492] INFO in app: info
[2018-09-04 21:50:37,492] WARNING in app: warn
[2018-09-04 21:50:37,492] ERROR in app: error
[2018-09-04 21:50:37,492] CRITICAL in app: critical

4. 参考

http://flask.pocoo.org/docs/1.0/logging/
https://docs.python.jp/3/library/logging.config.html#dictionary-schema-details
https://docs.python.jp/3/library/logging.html#logrecord-attributes
https://docs.python.jp/3/library/logging.handlers.html#timedrotatingfilehandler
https://devlights.hatenablog.com/entry/2018/04/19/233142

7
5
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
7
5