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