17
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】ロギングのベタープラクティス

Last updated at Posted at 2021-05-21

実装

同じ階層にmain.pylogger.pyがあるとします。

logger.py
import logging
import logging.handlers


def set_logger():
    logger = logging.getLogger()

    streamHandler = logging.StreamHandler()
    fileHandler = logging.handlers.RotatingFileHandler(
        "./logs/app.log", maxBytes=1000000, backupCount=5, encoding="utf-8"
    )

    formatter = logging.Formatter(
        '%(asctime)s| %(levelname)-5s | %(name)s.%(funcName)s.%(lineno)d | %(message)s'
    )

    streamHandler.setFormatter(formatter)
    fileHandler.setFormatter(formatter)

    logger.setLevel(logging.DEBUG)
    streamHandler.setLevel(logging.INFO)
    fileHandler.setLevel(logging.DEBUG)

    logger.addHandler(streamHandler)
    logger.addHandler(fileHandler)

    return logger

main.py
# 最初に定義
from logger import set_logger

if __name__ == "__main__":
    set_logger()

    ...
    ..
    .

各モジュールでの使用例

import logging


logger = logging.getLogger(__name__)


logger.debug("debug")
logger.info("info")
logger.warning("warn")
logger.error("error")
logger.critical("critical")

結果

コンソール
$ python /app/tmp/main.py 
2024-10-25 13:22:45,521| INFO  | functions.apicall_vad.54 | done: ./tmp/target.wav
2024-10-25 13:22:45,523| INFO  | functions._clear_dir.241 | done: clear ./tmp_splitted_wav
2024-10-25 13:22:45,526| INFO  | functions.split_wav_by_vad.132 | done: ./tmp_splitted_wav/0.wav
2024-10-25 13:22:45,527| INFO  | functions.split_wav_by_vad.132 | done: ./tmp_splitted_wav/1.wav
app.log
2024-10-25 13:23:01,511| INFO  | functions.apicall_asr.98 | done: ./tmp_combined_wav/2.wav
2024-10-25 13:23:07,337| DEBUG | functions.apicall_asr.89 | _json_data= {'data': ["brabrabra"], 'errors': []}
17
8
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
17
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?