LoginSignup
0
0

More than 3 years have passed since last update.

Pythonのロギング

Posted at

概要

PythonでロギングするLoggerクラス。

Loggerクラス

Logger.py
from logging import Formatter, handlers, StreamHandler, getLogger, DEBUG

class Logger:

    _unique_instance = None

    def __init__(self, name=__name__):
        self.logger = getLogger(name)
        self.logger.setLevel(DEBUG)
        formatter = Formatter("[%(asctime)s] [%(process)d] [%(name)s] [%(levelname)s] %(message)s")

        # stdout
        handler = StreamHandler()
        handler.setLevel(DEBUG)
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

        # file
        handler = handlers.RotatingFileHandler(filename = 'backup.log',
                                               maxBytes = 1048576,
                                               backupCount = 3)
        handler.setLevel(DEBUG)
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

    @classmethod
    def get_instance(cls):
        if not cls._unique_instance:
            cls._unique_instance = cls()

        return cls._unique_instance

    def debug(self, msg):
        self.logger.debug(msg)

    def info(self, msg):
        self.logger.info(msg)

    def warn(self, msg):
        self.logger.warning(msg)

    def error(self, msg):
        self.logger.error(msg)

    def critical(self, msg):
        self.logger.critical(msg)

使用例

  • インスタンスの作成/呼び出しはget_instance()を使う。
  • ロギングの出力は各メソッドを呼び出す。
UseLogger.py

from Logger import Logger

# 〜(中略)〜
logger = Logger.get_instance()

logger.error("some error message")
logger.debug("some debug message")

# 備考

  • Singletonになっているので、複数のモジュール内でインスタンスを使う場合も、get_instance()からインスタンスを取得すれば、インスタンスは1つしか作成されない。
0
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
0
0