はじめに
Pythonにはログ出力を行うlogging
モジュールが標準で備わっています。
このモジュールを利用するときには、ログの出力先や出力内容などを設定する必要があります。
しばらく使っていないと忘れてしまいそうなので、メモします。
ログ出力の設定方式とこの記事で取り扱う方式
logging
モジュールには、大きく2つの出力設定方式があります。
dictConfig()
とfileConfig()
という2つです。
dictConfig()
では、引数にditctionary形式で出力設定を与えます。
fileConfig()
では、ConfigParser形式(WindowsのINIファイルに似た形式)で出力設定を与えます。
fileConfig()
APIでの出力設定の方式はdictConfig()
での方式よりも古く、
将来、設定方式が拡張されるときにdictConfig()
のみになされるそうなので、
dictConfig()
方式を利用するのが良いそうです。
ということで、dictConfig()
方式での指定方法について情報を記載します。
ログ出力設定
dictionary形式で以下のように準備します。
-
version
は固定的に1を指定。 -
formatters
には出力文字列の書式を設定します。複数設定可能です。 -
handlers
には出力先(コンソールに出力するStreamHandler
やローテートして出力するRotatingFileHandler
など)を設定します。 -
logger
には、ロガー名と利用するハンドラとの対応づけを設定します。
# ログ出力設定
LOGGING = {
'version': 1,
'formatters': {
'simpleFormatter': {
'class': 'logging.Formatter',
'format': '%(asctime)s - %(name)s[%(levelname)s] %(message)s'
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'level': 'DEBUG'
},
'fileout': {
'class': 'logging.handlers.RotatingFileHandler',
'filename': 'dictlog.log',
'mode': 'a',
'maxBytes': 5000,
'backupCount': 5,
'formatter': 'simpleFormatter'
}
},
'loggers': {
'simpleExample': {
'handlers': ['fileout', 'console'],
'propagate': 0,
'level': 'INFO'
}
},
'root': {
'level': 'DEBUG',
'handlers': ['fileout']
},
}
ログ出力部分
import logging
import logging.config
### 上のLOGGINGの宣言をここに書く ###
# ログ出力設定をdictionary形式で指定する
logging.config.dictConfig(LOGGING)
# dictionary内に定義されているロガー名を指定する
logger = logging.getLogger('simpleExample')
logger.info("===== Application Start =====")
logger.info("===== Application End =====")
出力例
上の設定では、simpleExample
ロガーにて、ファイルとコンソールとの両方に出力するよう設定しています。
それぞれ次のように出力されます。
- ファイル
2019-06-09 20:33:20,090 - simpleExample[INFO] ===== Application Start =====
2019-06-09 20:33:20,091 - simpleExample[INFO] ===== Application End =====
- コンソール
===== Application Start =====
===== Application End =====
おわりに
ログはプログラムの動作を追うのにとても有効な情報となります。
短いプログラムであってもログを出力するようにしていきたいものです。
参考情報
- 設定のフォーマット
- 出力する文字列の書式設定