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

More than 3 years have passed since last update.

python loggingメモ

Last updated at Posted at 2021-10-21

##動作環境
macbook pro
python version 3.8.3

##loggerの構成
・ロガー→ログのレコードを生成する役割がある
・ハンドラ→ログレコードを出力する
・フォーマッタ→ログレコードを整形する
・フィルタ→ログレコードを処理するか否かの条件を定義する

##logger使い方

log_test1
import logging
import sys

#ロガーを生成
logger = logging.getLogger(__name__)

#ハンドラを生成
sh = logging.StreamHandler(sys.stdout)
# 出力レベルを設定
sh.setLevel(logging.WARNING)

#フォーマッタを定義
fmt = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s", "%Y-%m-%dT%H:%M:%S")
# フォーマッタをハンドラに紐づける
sh.setFormatter(fmt)

#ハンドラをロガーと紐づける
logger.addHandler(sh)
fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s"
logging.basicConfig(level=logging.DEBUG, format=fmt)

簡単に使うには

log_test1
import logging

logger = logging.getLogger(__name__)
fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s"
logging.basicConfig(level=logging.DEBUG, format=fmt)

##フォーマットについて

ログレベル

logging.debug('debug') #levelno->10
logging.info('info') #levelno->20
logging.warning('warning') #levelno->30
logging.error('error') #levelno->40
logging.critical('critical') #levelno->50

主な変数

%(asctime)s
%(message)s
%(created)f
%(filename)s
%(funcName)s
%(levelname)s
%(lineno)d

##参考にしたサイト
https://hackers-high.com/python/logging-overview/
https://srbrnote.work/archives/4472

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