Python - Python3 loggingで発生した--- Logging error --- の例外キャッチ方法|teratail
現在様々な国の言葉を取得し、扱う機能を実装しているのですが、その過程でPythonのlogging機能に出力した際、以下のエラーメッセージがコンソールにのみ出てきており、例外にキャッチできず、logが出力できない問題が発生しております。
この方の結論
結局の所logging内で例外が発生した場合、拾う手段が存在しないように感じます。(証明できる資料を探したのですが、探し方が悪いのか見つかりませんでした・・・)
ちょっと調べてみた。
--- Logging error --- をキーにして調べれば見つかるんじゃないかな
コードは以下にあった
code:handleError on logging/__init__.py
class Handler(Filterer):
...
def handleError(self, record):
"""
Handle errors which occur during an emit() call.
This method should be called from handlers when an exception is
encountered during an emit() call. If raiseExceptions is false,
exceptions get silently ignored. This is what is mostly wanted
for a logging system - most users will not care about errors in
the logging system, they are more interested in application errors.
You could, however, replace this with a custom handler if you wish.
The record which was being processed is passed in to this method.
"""
if raiseExceptions and sys.stderr: # see issue 13807
t, v, tb = sys.exc_info()
try:
sys.stderr.write('--- Logging error ---\n')
logging.Handler クラスの handleError メソッドで実装されているので、渡されたデータをHandlerの対象(コンソールとかファイルとか)に保存する形式にシリアライズできない場合のエラーを処理する実装になっている。
ここで発生したUnicodeEncodeErrorを強制的にログ出力可能にするには、この handleError メソッドをオーバーライドしてfallbackする仕組みを書けばよさそう。 独自の handleError で例外を捕まえて、例外が起きないようにrecordに処理を加えてから self.emit(record) を呼び直せば期待する動作が実現できそう。
code:python
def handleError(self, record):
t, v, tb = sys.exc_info()
if isinstance(t, UnicodeEncodeError):
# fallback処理としてrecordを修正する
self.emit(record)
else:
super().handleError(record)
上記をまとめて回答してみました
タグ