0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Last updated at Posted at 2025-03-08

nysimplelog

Python 3.10+

nysimplelog は、ロギングのためのシンプルなPythonライブラリです。標準のPython logging.basicConfig に依存せずに、コンソールとファイルの両方にログを出力します。ロギングは、異なるモジュール間で設定できます。

1. 要件

  • Python 3.10以上(完全な型ヒントサポートのため)
  • tzdata(Windowsでタイムゾーンサポートに必要)

2. インストール

pipでインストールします:

pip install nysimplelog

3. 使い方

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

メインプログラムの場合:

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

モジュールの場合:

from logging import getLogger

3.2 ロガーの作成

指定された名前のロガーを返します。ロガー名に __name__ を使用することで、モジュール名を使用できます。

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

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

カスタム設定でロガーを初期化します。この関数は設定済みのロガーを返します。

logger = initialize_simple_logger(
    name="example",
    log_dir="logs",
    fmt="%(asctime)s %(levelname)s %(name)s - %(message)s", # Custom format
    datefmt="%Y-%m-%dT%H:%M:%S", # Custom date format
    tz="Asia/Tokyo"
    level="DEBUG",
    file_handler_level=WARNING, # File logs warnings and above
    maxBytes=1024 * 1024, # 1MB (default is 10MB)
    backupCount=5, # 5 log files (default is 2)
)

オプション

パラメータ 説明
name ロガーの名前。
log_dir ログファイルのディレクトリ。デフォルト: "logs"
filename ログファイル名。デフォルト: "{log_dir}/{name}.log"
fmt ログメッセージのフォーマット。デフォルト: "%(asctime)s %(levelname)s %(name)s - %(message)s"
datefmt 日付フォーマット。デフォルト: ISO-8601(例: "2023-05-27T07:20:32.798+09:00")。
tz ログタイムスタンプのタイムゾーン(例: "UTC", "Asia/Tokyo")。デフォルト: None(ローカル時間を使用)。
formatter カスタムフォーマッター。デフォルト: None(ISO8601_Formatterを使用)。
level ロガーレベル(intまたはstr)。デフォルト: logging.INFO
stream_handler_level ストリームハンドラレベル。デフォルト: None の場合、パラメータ level が使用されます。
file_handler_level ファイルハンドラレベル。デフォルト: None の場合、パラメータ level が使用されます。
maxBytes ローテーション前の最大ファイルサイズ。デフォルト: 10MB
backupCount バックアップログファイルの数。デフォルト: 2

注意: Windowsで特定のタイムゾーンで tz パラメータを使用するには、pip install tzdata を実行してください。

3.4 メッセージのロギング

詳細はPythonのloggingドキュメントを参照してください。標準のロギングメソッドを使用します:

logger.debug("Debug message")
logger.info("Info message")
logger.warning("Warning message")
logger.error("Error message")

4. 例

4.1 ディレクトリ構造

examples/example_usage.py
examples/mypackage/__init__.py

完全なサンプルプロジェクトについては、GitHubリポジトリのexamplesフォルダを参照してください。

4.2 モジュールの例

# examples/mypackage/__init__.py
from logging import getLogger

logger = getLogger(__name__)

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

4.3 メインプログラム

# examples/example_usage.py
from logging import getLogger, WARNING, INFO, DEBUG
from nysimplelog import initialize_simple_logger

import mypackage

# Main logger with different levels for stream and file
logger = initialize_simple_logger(
    name="main",
    level=DEBUG,
    stream_handler_level=INFO,  # Console logs info and above
    file_handler_level=WARNING  # File logs warnings and above
)

# Module-specific logger
initialize_simple_logger(name=mypackage.__name__, level=DEBUG)

logger.debug("This is a debug message")  # Not displayed
logger.info("This is an info message")   # Only in file (if level allows)
logger.warning("This is a warning")      # Console and file
mypackage.hello()                        # Depends on mypackage logger

4.4 出力

コンソール:

2025-03-02T18:01:28.413+09:00 INFO main - This is an info message
2025-03-02T18:01:28.414+09:00 WARNING main - This is a warning
2025-03-02T18:01:28.414+09:00 DEBUG mypackage - Hello, world!

ファイル logs/main.log:

2025-03-02T18:01:28.414+09:00 WARNING main - This is a warning

ファイルは logs/ にローテーション付きで保存されます(例: main.logmain.log.1 など)。

5. 特徴

  • ロギングは異なるモジュールごとに設定可能です。
  • 標準出力とファイル出力をサポートします。
  • ログファイルのローテーションをサポートします。
  • デフォルトの日付形式としてISO-8601を使用します。

6. 開発

6.1 仮想環境のセットアップ

# Create virtual environment
python -m venv venv

# Activate virtual environment
# Windows:
venv\Scripts\activate
# macOS/Linux:
source venv/bin/activate

6.2 依存関係のインストール

pip install -r requirements-dev.txt

6.3 テストの実行

pytest

6.4 パッケージのビルド

python -m build

7. 著者

開発者: Naoyuki Yoshinori

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?