dimanche 6 décembre 2020

Python - Code structure (Design Pattern) for a wrapper

I am new to python and I have implemented a wrapper for logging in a python module.

For now, it is a simple logger.py file with a few methods inside.

import json
...
this = sys.modules[__name__]
this.logger = None

def initialize():
  if environment = local_dev
    ... do some specific setup
    this.logger = ...
  else
    ... do another setup
    this.logger = ...

def log(level, message, *args, **kwargs):
  if environment=local_dev # Not optimal. I don't want to have to evaluate that every time I log
    ... log in a certain way
  else
    ... log in a prod ready way

def debug(...):
  return log(...)

def info(...):
  return log(...)

Ideally, what i would want is to be able to use my logger the following way.

In main.py

from common.logging import logger

logger.initialize()

In any file

from common.logging import logger

mylogger = logger.getLogger()
mylogger.debug(...)

What I want is :

  • When getLogger is called, I want it to return a proper module with a log function that reflects whether or not i'm in a local dev environment or not.
  • I don't want to have to do some if statements in my log function. I want the logger to automatically be created so that the proper log function is defined and that condition doesn't get evaluated each time log is being called.

I'm not exactly sure if using a class instead of a module here would be optimal. I've opted for a module since i was intending on having only one instance of the logger throughout the application.

I'm thinking maybe I should have some sort of factory pattern that would create the logger object correctly, once, based on the environment.

Any design ideas for this would be greatly appreciated. Thanks

Aucun commentaire:

Enregistrer un commentaire