Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - use logger inside function from module calling it

Tags:

python

logging

Let's say I have code like this:

ModuleA.py:

import logging
logger = logging.getLogger('A')

def utility_func():
    logger.info('hi')
print utility_func()

ModuleB.py:

import logging
logger = logging.getLogger('B')
from ModuleA import utility_func

print utility_func()

When utility_func is called from within ModuleA.py I want it to use the 'A' logger, and when it's called from ModuleB.py I want it to use the 'B' logger.

Is there a way to do this? Or a better way to set things up?

Update:

What about the idea of changing utility_func to:

def utility_func():
    logging.info('hi')

Would that bubble up to whichever log the calling code is using?

like image 280
Greg Avatar asked Jun 28 '26 13:06

Greg


1 Answers

Here's what I ended up going with. But I'm still curious to hear if there's a more elegant way.

ModuleB.py:

import logging
import ModuleA

logger = logging.getLogger('B')
ModuleA.logger = logger

print ModuleA.utility_func()
like image 200
Greg Avatar answered Jul 01 '26 02:07

Greg