【Python】 Python ~ 標準ログ / Logging ~

■ サンプル

例1:簡易版

import logging
import sys

LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'

logging.basicConfig(
  level=logging.INFO, stream=sys.stdout, format=LOG_FORMAT)

logging.info("Start")
logging.info("End")

出力結果

2020-05-08 20:31:38,665 - root - INFO - Start
2020-05-08 20:31:38,732 - root - INFO - End

例2:標準出力

import logging
from logging import getLogger, StreamHandler, Formatter

LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'

logger = None

def initialize_logger():
  global logger
  if logger is not None:
    return

  logger = getLogger("LoggerDemo")
  logger.setLevel(logging.DEBUG)
  stream_handler = StreamHandler()
  stream_handler.setLevel(logging.DEBUG)
  handler_format = Formatter(LOG_FORMAT)
  stream_handler.setFormatter(handler_format)
  logger.addHandler(stream_handler)

initialize_logger()
logger.debug("Hello World!")
logger.info("Hello World!!")
logger.warning("Hello World!!!")
logger.error("Hello World!!!!")
logger.critical("Hello World!!!!")

出力結果

2020-02-03 23:12:37,535 - LoggerDemo - DEBUG - Hello World!
2020-02-03 23:12:37,536 - LoggerDemo - INFO - Hello World!!
2020-02-03 23:12:37,536 - LoggerDemo - WARNING - Hello World!!!     
2020-02-03 23:12:37,537 - LoggerDemo - ERROR - Hello World!!!!      
2020-02-03 23:12:37,538 - LoggerDemo - CRITICAL - Hello World!!!! 

参考文献

https://qiita.com/mimitaro/items/9fa7e054d60290d13bfc

関連記事

global変数
https://dk521123.hatenablog.com/entry/2019/12/12/232749