NI6
NI6

Reputation: 2897

Give logger object as a parmeter when importing a module

Let me describe the following scenario :

I'm using a module of my own in a few projects. This module holds classes and additional sub modules (again of my own).

I want to write log messages in the module and its sub files, but give the logger object as a parameter when importing the module in each project.

All the loggers I am using have similar interface (same mthods etc...).

Is there a way to implement this concept?

Thanks in advance!

Upvotes: 1

Views: 34

Answers (1)

Mikhail Gerasimov
Mikhail Gerasimov

Reputation: 39576

Instead of passing logger object as param to module, you can use universal function that returns needed logger based on loggers's id. It's how logging system implemented in standard Python logging module.

logging.getLogger(name=None) (link) uses to get logger object, based on given name. Usually name is module name: logger = logging.getLogger(__name__).

In case you don't want to use standard logging, you can at least use this concept in your projects.

In logging module:

loggers = {}

def get_logger(name):
    if name not in loggers:
        loggers[name] = Logger()  # create logger instance for name
    return loggers[name]

In projects:

import get_logger  # use this function in projects to get logger instances

logger = get_logger("project 1 logger id")  # in project 1
logger = get_logger("project 2 logger id")  # in project 2

Upvotes: 1

Related Questions