Pythonのログ関数の使い方-その1
Pythonの標準ライブラリのlogginモジュールの使い方です。
Level1 ログを書式を指定して表示させる
# -*- coding:utf-8 -*- import logging logging.basicConfig( # ログレベルを指定 level=logging.DEBUG, # ログの書式を指定 左から時刻、ログレベル、モジュール名、関数名、行数、内容 format="%(asctime)s %(levelname)s %(module)s %(funcName)s %(lineno)d %(message)s") def test(): logging.error('error!') logging.debug('debug!') test()
実行結果
コンソールに書式指定の通りに表示されます。
# python log.py 2014-10-15 14:19:32,155 ERROR log test 12 error! 2014-10-15 14:19:32,155 DEBUG log test 13 debug!
Level2 ログをファイルを指定して出力させる
ログ用のファイルを作成し、そのファイルにログの中身を出力します。
# -*- coding:utf-8 -*- import logging logging.basicConfig( # ログレベルを指定 level=logging.DEBUG, # ログを保存するファイルを指定 filename = 'log.txt', # ログの書式を指定 左から時刻、ログレベル、モジュール名、関数名、行数、内容 format="%(asctime)s %(levelname)s %(module)s %(funcName)s %(lineno)d %(message)s") def test(): logging.error('error!') logging.debug('debug!') test()
実行結果
ファイルに指定の通りに出力されます。
# python log.py # tail log.txt 2014-10-15 14:29:32,985 ERROR log test 14 error! 2014-10-15 14:29:32,985 DEBUG log test 15 debug!