HOW #9 – Python logging

Logging is important part of each project. With logs, developer or customers are able to see events happened in the past.

Small example: lets say, customer calls you that two week old transactions were not processed and are still stuck in the system. You as a developer thanks to the logging easily detected where the problem was and fixed it.

Python built-in logging library comes with multiple settings:

  • multiple log levels (info, warning, error ...)
  • logging possible to different streams (files, rotating files, sockets, standard out ...)
  • endless possibilities setting up information log can contain

In the code below, the singleton logging class is implemented:

import logging

class Logs:
       """
       this is singleton class
       """
       _singleton = None


       def __init__(self, logger_name):
              if self.__initialized:
                  return
              self.__initialized = True
              self.__logger_name = logger_name
              stream_log_handler = logging.StreamHandler
              log_formatter = logging.Formatter(u'%(asctime)s - %(name)s - %(levelname)s - %(process)d - %(message)s
              stream_log_handler.setFormatter(log_formatter)
              self.logger = logging.getLogger(logger_name)
              self.logger.addHandler(stream_log_handler)
              self.logger.setLevel(logging.DEBUG)


       def __new__(cls, logger_name):
              if not cls._singleton:
                     cls._singleton = super(Logs, cls).__new__(cls)
                     cls._singleton.__initialized = False
                     return cls._singleton

       @classmethod
       def create_logger(cls, logger_name):
              logger = cls(logger_name)
              return logger.logger

I am setting the logger:

  • output to the stream only (standard output) - I am using this setting for GCP projects, as this logs are stored by Google, there is no need to store them to the files separately
  • use format: u'%(asctime)s - %(name)s - %(levelname)s - %(process)d - %(message)s'
  • set logging level to debug - meaning that lover level info log message will not be logged

Then, wherever in the project you can log using this snippet:

from classes.logs import Logs

logger = Logs.create_logger()

if __name__ == '__main__':
      logger.debug("Hello world!")

And thats it. Hope the ones, which were not logging until now, will start :)))