LoginSignup
29
27

More than 5 years have passed since last update.

Flaskでloggingの設定を外部ファイルから読み込む

Last updated at Posted at 2014-09-23

Flaskで普通にloggingをする場合、Flask logging exampleのように、

app.py
app = Flask(__name__)
app.logger.debug("test message")

のようにすれば簡単に出来る。
しかし、loggingの外部ファイルから設定を読み込むfileConfig

fileConfig
import logging.config
logging.config.fileConfig("config.ini")

dictConfigが使えない

dictConfig
import logging.config
import yaml
logging.config.dictConfig(yaml.load(open("config.yaml").read()))

やると当然AttributeErrorとなる。

app.logger.fileConfig('./config.ini')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-29-70995f52c865> in <module>()
----> 1 app.logger.fileConfig('./config.ini')

AttributeError: 'DebugLogger' object has no attribute 'fileConfig'

そのため、app.logger.addHandlerでコードでいちいち書かないとだめっぽく感じる。

しかし、app.loggerloggingをラップしただけなので、app.run()する前にlogging.config.fileConfig()を呼べば設定は反映される。

設定ファイル

基本的にはやはりドキュメントを参照する
yamlの書き方は、handlersに使用するclass(この場合はlogging.StreamHandlerlogging.TimedRotatingFileHandler)のコンストラクタのキーワード引数に対応させれば良い。

個人用テンプレ

iniよりyamlの方が好きなのでyamlを使う

config.yaml
version: 1

formatters:
  customFormatter:
    format: '[%(asctime)s]%(levelname)s - %(filename)s#%(funcName)s:%(lineno)d: %(message)s'
    datefmt: '%Y/%m/%d %H:%M:%S'

loggers:
  file:
    handlers: [fileRotatingHandler]
    level: DEBUG
    qualname: file
    propagate: no

  console:
    handlers: [consoleHandler]
    level: DEBUG
    qualname: console
    propagate: no

handlers:
  fileRotatingHandler:
    formatter: customFormatter
    class: logging.handlers.TimedRotatingFileHandler
    level: DEBUG
    filename: log/debug.log
    encoding: utf8
    when: 'D'
    interval: 1
    backupCount: 14

  consoleHandler:
    class: logging.StreamHandler
    level: DEBUG
    formatter: customFormatter
    stream: ext://sys.stdout

root:
  level: DEBUG
  handlers: [fileRotatingHandler,consoleHandler]

最後のrootを忘れるとうまく動かない
これに気付かずはまってしまった

29
27
3

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
29
27