0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonの標準ログ出力機能を利用するときの設定

Last updated at Posted at 2019-06-09

はじめに

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 =====

おわりに

ログはプログラムの動作を追うのにとても有効な情報となります。
短いプログラムであってもログを出力するようにしていきたいものです。

参考情報

  • 設定のフォーマット

  • 出力する文字列の書式設定

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?