【Python】logging サンプルコード【ログ出力】

ログ出力

import logging

logging.basicConfig(filename='./logs/command.log',
                        encoding='utf-8', level=logging.DEBUG)

logging.debug('でばっぐ')
logging.info('いんふぉ')
logging.warning('わーにんぐ')
logging.error('えらー')
logging.critical('くりてぃかる')

basicConfigでRotatingFileHandlerを使う

作ったハンドルをbascConfigで使うこともできます。

rh = logging.handlers.RotatingFileHandler(
    './logs/command.log',
    encoding='utf-8',
    maxBytes=1000,
    backupCount=5
)

# ハンドラーの閾値を設定
rh.setLevel(logging.INFO)

# フォーマットの設定
rh.setFormatter(logging.Formatter(
    '%(asctime)s | %(levelname)8s | File "%(pathname)s", line %(lineno)d, in %(message)s'
))

logging.basicConfig(handlers=[rh])

個別のログ設定

ログを個別で出したり、basicConfigで出てくる基本的なログを出したくない場合

import logging
import logging.handlers

# ロガーを取得
logger = logging.getLogger(__name__)

# ロガーの閾値を設定
logger.setLevel(logging.INFO)

rh = logging.handlers.RotatingFileHandler(
    './logs/command.log',
    encoding='utf-8',
    maxBytes=1000,
    backupCount=5
)

# ハンドラーの閾値を設定
rh.setLevel(logging.INFO)

# フォーマットの設定
rh.setFormatter(logging.Formatter(
    '%(asctime)s | %(levelname)8s | File "%(pathname)s", line %(lineno)d, in %(message)s'
))

# ハンドラーをロガーに追加
logger.addHandler(rh)

# ログの出力
logger.debug('でばっぐ')
logger.info('いんふぉ')
logger.warning('わーにんぐ')
logger.error('えらー')
logger.critical('くりてぃかる')

RotatingFileHandlerはファイルのマックスサイズを決めてファイルをローテーションしてくれるので使いやすい。

ログフォーマットについて↓
https://docs.python.org/ja/3/library/logging.html#logrecord-attributes

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です