pythonでlogging
ツール的に使っているpythonだが、処理速度を上げるためにマルチスレッド化させたり、ツール規模が大きくなってモジュール化させたり、少し凝った事をすると、printでの実行ログ出力では物足りなくなる。
pythonではloggingの仕組みも標準で組み込まれている。
準備
1 2 | import logging.config logging.config.fileConfig('logging.conf') |
logging.confにログ出力設定を書いておき、loggingを初期化する。
初期化とは、ログの出力情報(出力先、出力フォーマットなど)を設定すること。
logging.confの内容は下記の通り
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | [loggers] keys=root [handlers] keys=consoleHandler,fileHandler [formatters] keys=simpleFormatter [logger_root] level=INFO handlers=consoleHandler,fileHandler [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [handler_fileHandler] class=FileHandler level=DEBUG formatter=simpleFormatter args=('Log.txt', 'w', 'utf-8', False) [formatter_simpleFormatter] format=%(asctime)s [%(levelname)-5s] (%(module)s).(%(funcName)s).(%(lineno)d) %(message)s |
コンソールとファイルにログを出力している。
もっとシンプルに初期化したい時は、logging.basicConfigを呼び初期化する。
1 2 3 4 5 | import logging logging.basicConfig( format='%(asctime)s [%(levelname)-7s] (%(funcName)s) %(message)s', level='INFO', ) |
コンソールに処理時間とログレベルと関数名、メッセージを表示する。
処理時間が表示されるだけでも、便利なことも多い。
関数名が表示されるので、処理状況を確認しやすい。
ログの出力
1 2 3 4 | logging.debug('debug message.') logging.info('information message.') logging.warn('warning message.') logging.error('error message.') |
loggingに用意されたショートカットメソッド(info,errorなど)で簡単にログを出力できる。
ちなみに、上記の準備ではログレベルをINFOにしているため、ログ出力の例のdebug message.は出力されない。
各モジュールでのlogの実装
各モジュールでは、loggerを生成し、
そのloggerでメッセージを出力する。
1 2 3 | def another_function(): logger = logging.getLogger(<strong>name</strong>) logger.info('process start!') |
このように実装しておくことで、呼び出し元がログ出力を制御できる。
出力先を変えたり、出力すべきログレベルを変更したり、
それ用のhandlerを用意したりできる。
同じタグの記事
- BOM付きUTF-8からBOMを除去するpython
- jythonのヒープメモリ設定
- Kotlin1.2.50がリリースされていた
- macOSをHigh Sierraに更新した。スクリプト実行環境のバージョンは変わったのか
- macOSをMojaveに更新した。スクリプト実行環境のバージョンは変わったか
- pathlib.Pathを調べる
- pyenvでpython環境をインストール
- pyenvとvirtualenvでpython環境を構築
- python unpack
- python3で数値のlistを文字列のlistに変換
同じカテゴリの記事