简体   繁体   中英

Python logger with multiple modules

I want to create my custom logger class

import logging
class mylooger():
   def __init__(module_name):
       logger=logging.getlogger(module_name)

And i want use logger in my main file and two other files

main.py
test1.py
test2.py

i want to decide my logfile path in main.py and keep main.py, test1.py and test2.py file log in same file.

Now suppose later i want to import test1.py and test2.py in some other file eg main1.py. So i want to decide my logfile path from main1.py and keep main1.py, test1.py and test2.py log in same file.

That's not how stdlib logging is designed. If you want to use the same logger in multiple modules, just get the same logger:

# in main.py
logger = logging.getLogger("mylogger")

def main():
    ...
    logging.basicConfig(...)
    logger.info("some event")

And:

# in test1.py
logger = logging.getLogger("mylogger")

def some_lib_function():
    ...
    logger.debug("some other event")

The logging framework itself maintains a global mutable state so that these are resolving to the same loggers and hence the same formatters/handlers.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM