LoginSignup
2

More than 3 years have passed since last update.

Flask 1.1.x でlogging.getLoggerしようとしてハマった

Last updated at Posted at 2020-02-21

結論

appインスタンスを触れないところでログ出力するときは、
app.loggerを一度でも参照してから、
logging.getLogger("app")でロガーを取得する。

メモ

基本はこのように、app.loggerでログ出力すればよい。

app.py
from flask import Flask

app = Flask(__name__)

app.logger.warning("This is warning message.")
# => [2020-02-21 14:35:09,642] WARNING in app: This is warning message.

これは普通に動く。
でも、main以外のソースからappを触りたくないので
logging.getLogger でロガーを取得する。
ググって出る記事を見て下のようにした。

index.py
import logging 

log = logging.getLogger("flask.app")
log.warning("This is warning message.")
# => This is warning message.

だめ。出力されるけどなにも整形されず、たんにprintしたのと同じ。

1.1.xのドキュメントを見ると仕様が変わっていた。
app.name と同じ名称でロガーが登録されるらしい。
メインのソースファイル名がapp.py、初期化をFlask(__name__)としているので
getLogger("app")で取れるはず。

index.py
import logging 

log = logging.getLogger("app")
log.warning("This is warning message.")
# => This is warning message.

何故かこれもだめ。出力が整形されなかった。

いろいろいじった結果、こうすれば動いた。

app.py
from flask import Flask

app = Flask(__name__)
app.logger.warning("適当に1回ログを出しておく")
index.py
import logging 

log = logging.getLogger("app")
log.warning("This is warning message.")
# => [2020-02-21 14:35:09,642] WARNING in index: This is warning message.

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