LoginSignup
0
2

More than 3 years have passed since last update.

【Python】loggingの出力結果をログファイルに出力する

Last updated at Posted at 2021-04-02

pythonでloggingを使ってログを外部ファイルに出力させる方法について、手こずったので備忘録的に残しておきます。

■やりたいこと

・loggingモジュールを使って、ログの内容を「test○○○.log」に出力する
・loggingの設定情報については、以下の2パターンについて検討する
 1.ソースに直接記述する場合
 2.「logging.conf」を作成し、参照させる場合
・Windows環境なので、文字化けを防ぐため、文字コードをShift_JIS (CP932) からUTF-8にエンコードする設定を入れる

■環境

OS:Windows10
バージョン:Python 3.9.2

■ディレクトリ構成

[main]
  ├──logging_test01.py
  ├──logging_test02.py
  |
  ├──[conf]
  |    └──logging.conf
  |
  └──[logs]
       ├──test001.log
       └──test002.log

■手順

1.loggingをインストール

コマンドプロンプトを起動し、以下のコマンドを実行

pip install logging --user
※もしくは、py -m pip install logging

2.パターン1(loggingの設定情報をソースに直接記述する場合)

パターン1のソース

logging_test01.py
import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

#ファイルへ出力するハンドラーを定義
fh = logging.FileHandler(filename='./logs/test001.log', encoding='utf-8')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
#rootロガーにハンドラーを登録する
logger.addHandler(fh)

logger.debug("ログに出力")
logger.info("ログに出力")
logger.warning("ログに出力")
logger.error("ログに出力")

パターン1の出力結果

test001.log
2021-04-02 14:49:05,471 - DEBUG - ログに出力
2021-04-02 14:49:05,471 - INFO - ログに出力
2021-04-02 14:49:05,471 - WARNING - ログに出力
2021-04-02 14:49:05,471 - ERROR - ログに出力

3.パターン2(「logging.conf」を作成し、参照させる場合)

パターン2のソース

logging_test02.py
import logging.config

logging.config.fileConfig("./conf/logging.conf")
logger = logging.getLogger()

logger.debug("ログに出力")
logger.info("ログに出力")
logger.warning("ログに出力")
logger.error("ログに出力")

パターン2のconfファイル

logging.conf
[loggers]
keys = root

[handlers]
keys = fileHandler

[formatters]
keys = simpleFormatter

[logger_root]
level = DEBUG
handlers = fileHandler

[handler_fileHandler]
class = FileHandler
formatter = simpleFormatter
args = ('./logs/test002.log', 'a', 'utf-8')

[formatter_simpleFormatter]
format = %(asctime)s %(levelname)s %(message)s

パターン2の出力結果

test002.log
2021-04-02 15:00:37,780 DEBUG ログに出力
2021-04-02 15:00:37,780 INFO ログに出力
2021-04-02 15:00:37,780 WARNING ログに出力
2021-04-02 15:00:37,780 ERROR ログに出力

■まとめ

pythonの経験が少なかったので、logging.confのパス指定に手こずったり、logging.confの中にコメントを書いておくとエラーになるなどいろいろと勉強になった。

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