Published on

Python Logging Mixin

Authors

While wrapping up some Python code today I wanted to add traceability in the form of logging. Being fairly new to Python a did a quick search on this and came across this excellent answer.

The idea is to create a mixin as defined in the answer:

import logging
import logging.config
import os
import sys
from os import path

__ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
# adjust the below to place the log wherever you want to relative to this class
__TOP_LEVEL_PATH = path.join(__ROOT_DIR, '../..')

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] - %(module)s -  %(message)s",
    handlers=[
        logging.StreamHandler(stream=sys.stdout),
        logging.FileHandler("{0}/{1}.log".format(__TOP_LEVEL_PATH, "trading_engine"))
    ])


# This class could be imported from a utility module
class LogMixin(object):
    @property
    def logger(self):
        name = '.'.join([__name__, self.__class__.__name__])
        return logging.getLogger(name)

    def log_stacktrace(self, message, error):
        self.logger.error(message)
        self.logger.exception(error)

You then use it by making the class that needs the logger to inherit from it:

class A(LogMixin):
    def some_method():
        self.logger.debug('Hello from A')

While working with a class that has this you can easily adjust the logging level on the fly as below:

some_class = A()
some_class.logger.setLevel(logging.DEBUG)
some_class.logger.addHandler(logging.StreamHandler())
some_class.some_method()