How can I get logging from within a logger in one module and still use a log decorator?
I have this basic log decorator in logger.py:
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
file_handler = logging.FileHandler("dec_log.log")
logger.addHandler(file_handler)
def log(func):
def wrapper(*args, **kwargs):
func_info = f"\n{func.__name__}, {func.__module__}"
logger.info(func_info)
res = func(*args, **kwargs)
return res
return wrapper
This works fine, but then sometimes I want to log something within the function of another module.
So, for example, if I have main.py set up like this:
logg = logging.getLogger(__name__)
logg.setLevel(logging.DEBUG)
log_format = logging.Formatter(
"%(levelname)s:%(lineno)d:%(message)s",
)
file_handler = logging.FileHandler("main_log.log")
file_handler.setFormatter(log_format)
logg.addHandler(file_handler)
@log
def divide_func(a, b):
try:
res = a / b
except DivisionByZeroError:
logg.critical(f"Can't divide by zero: {a} / {b}")
else:
return res
This doesn't work. I get dec_log.log file with that info, but I don't get a main_log.log file with the logger info. What am I doing wrong?
I was able to come up with a way to make it sort of work, but not sure if this would be considered a proper method:
In main.py
:
From logger import logger, log
@log
def divide_func(a, b):
try:
res = a / b
except DivisionByZeroError:
logger.critical(f"Can't divide by zero: {a} / {b}")
else:
return res
This doesn't do exactly what I want, but close enough for now that I can stop messing with setting up a logger.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.