mrser
mrser

Reputation: 107

Avoid singleton pattern in logging module

For example, i have some script test1.py with code like this:

import logging
from logging.handlers import RotatingFileHandler
import some_module

handler = RotatingFileHandler('TEST1.log', maxBytes=18000, backupCount=7) 
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logging.getLogger("some_module").addHandler(handler)

do_something():
some_module.do_smth()

do_something()

And I have another script test2.py with code like this:

import logging
from logging.handlers import RotatingFileHandler
import some_module

handler = RotatingFileHandler('TEST2.log', maxBytes=18000, backupCount=7) 
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logging.getLogger("some_module").addHandler(handler)

do_something():
some_module.do_smth_else()

do_something()

Then i import both scripts in file app.py, which can call one of the scripts for some reasons.

The problem is, that all log messages for module some_module from script test1.py are written to both log files: and TEST1.log, and TEST2.log.

As i understood, the problem is about singleton pattern, so module logging is something like global module for all my scripts, which are working in the same process. So, when i import test1.py to app.py it adds handler for some_module first time, then, when i import test2.py to app.py, it adds handler for some_module another time, and this module now has 2 handlers.

Is there a way to add handlers for this module separately, so all debug messages, which are being called by test1.py, will be written in TEST1.log, but not in TEST2.log.

UPDATE:

In my case i am trying to do it with this module, and it seems, that with it it's not working:

logging.getLogger("TeleBot.test1").setLevel(logging.DEBUG)
logging.getLogger("TeleBot.test1").addHandler(handler)

And nothing is being written in my log file, but if i just do simply:

logging.getLogger("TeleBot").setLevel(logging.DEBUG)
logging.getLogger("TeleBot").addHandler(handler)

It's working, but, as i mentioned in the question, it writes debug messages to all files. So, is it a bug in this particular module?

Upvotes: 2

Views: 2505

Answers (1)

Martin Valgur
Martin Valgur

Reputation: 6322

Doing logging.getLogger("some_module") in both files returns the same Logger object as you have already observed.

To get a separate Logger in each file simply provide a different name in getLogger() each time.

E.g. in test1.py

logging.getLogger("some_module.test1").addHandler(handler)

and in test2.py

logging.getLogger("some_module.test2").addHandler(handler)

Upvotes: 1

Related Questions