LoginSignup
0
0

シンプルなロギングライブラリ for Python Best Practices

Last updated at Posted at 2023-05-26

logging_support

logging_support は Python のシンプルなロギングライブラリです。本ライブラリはログデータをコンソールとファイルの両方に出力します。ロギングの設定は Python 標準ライブラリ loggingbasicConfig を使用せずに、モジュール単位で設定します。

1. インストール

pip install https://github.com/naoyoshinori/logging_support/archive/main.zip

2. 使用方法

2.1 パッケージのインポート

メインプログラムでロギングする場合

from logging import getLogger, WARNING, INFO, DEBUG
from logging_support import initialize_simple_logger

モジュールでロギングする場合

from logging import getLogger

2.2 ロガーの作成

logger = getLogger(__name__)
  or
logger = getLogger("example")

ロガー名に __name__ を使用することで、モジュール名を設定できます。

2.3 シンプルロガーの初期化

ロガーは以下のようにメインプログラムで初期化します。 name にモジュール名を設定します。 dir にログデータを保存するディレクトリを設定します。

initialize_simple_logger(
    name="example",
    dir="logs",
    fmt="%(levelname)s:%(name)s:%(message)s",
    datefmt="%Y-%m-%dT%H:%M:%S",
    level="WARNING",
    handler_level=DEBUG,
    maxBytes=0x7FFF,
    backupCount=2,
)

2.4 オプション一覧

キーワード 概要
name ロギング用の名前を設定します。
dir ロギングファイルを保存するフォルダを設定します。デフォルトのディレクトリは 'logs' です。
filename ロギングに使用するファイル名を設定します。デフォルトのファイル名は '{dir}/{name}.log' です。
fmt ロギングのフォーマットを設定します。 デフォルトの書式は "%(asctime)s %(levelname)s %(name)s - %(message)s"
datefmt 日付けの書式を設定しいます。デフォルトは ISO-8601 Format.
level ロギングのレベルを設定します。レベルは int または str である必要があります。
handler_level ロギング用ハンドラーのレベルを設定します。レベルは int または str である必要があります。
maxBytes ロギング用のファイルサイズ。デフォルトは32767(0x7FFF)byte。
backupCount ロギング用のバックアップ回数。デフォルトは2ファイル。

2.5 Logging

ロギングの詳細は Python 標準ライブラリ logging のドキュメントを参照してください。

logger.debug("debug message.")
logger.info("info message.")
logger.warning("warning message.")
logger.error("error message.")

2.6 サードパーティライブラリの場合

サードパーティライブラリでもログ出力を設定できます。

from logging import getLogger, WARNING, INFO, DEBUG
from logging_support import initialize_simple_logger

import selenium

initialize_simple_logger(name="selenium", level=DEBUG)
  or
initialize_simple_logger(name=selenium.__name__, level=DEBUG)

3. Example

Example のディレクトリ構造です。

example
│  example.py
│  
└─mypackage
   __init__.py

ここでは mypackage の例を紹介します。mypackage では Python 標準ライブラリ logging の getLogger を使用します。

# mypackage/__init__.py
from logging import getLogger

logger = getLogger(__name__)

def hello():
    logger.debug("hello, world!")

メインプログラムの例です。ここではモジュール毎にロガーを初期化します。Python 標準ライブラリ logging のbasicConfig を使用した場合、すべてのログが出力される問題があります。

# example.py
from logging import getLogger, WARNING, INFO, DEBUG
from logging_support import initialize_simple_logger

import mypackage

logger = getLogger("main")

initialize_simple_logger(name="main", level=DEBUG)
initialize_simple_logger(name=mypackage.__name__, level=DEBUG)

logger.debug("message")

mypackage.hello()

本ライブラリでは、ログデータをコンソールに表示します。

2023-05-27T07:20:32.798+09:00 DEBUG main - message
2023-05-27T07:20:32.798+09:00 DEBUG mypackage - hello, world!

さらに、ログデータをファイルとして出力します。Example の場合 logs/main.loglogs/mypackage.log というファイルが作成されます。

example
│  example.py
│  
├─mypackage
│  __init__.py
│      
└─logs
   main.log
   mypackage.log
0
0
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
0