Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Pythonのロギング

More than 1 year has passed since last update.

概要

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つしか作成されない。
crnls1985
インフラエンジニアです(Windows/Linux/Python/C#/Ansible)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away