简体   繁体   中英

Python - creating a logger if one doesn't exist

Often I will use a log in python with the following setup:

logging.basicConfig(
    format="(%(levelname)s) %(module)22s :  %(message)s",
    datefmt="%m/%d/%Y %I:%M:%S %p",
    level=logging.INFO,
)
log = logging.getLogger(__name__)

Sometimes I have a module m.py which can either be run by itself, or it can be called by another module.

If the module m.py is called as itself then I need all the setup outlined above, however, if m.py is called by a different module then the above isn't necessary, I can just have

log = logging.getLogger(__name__)

and it will inherit the logger that was created in the script that called m.py .

What I would like to know, is how to I have a setup which will take into account both of these scenarios for the script m.py ?

If my understanding of your problem is correct, you can use the if (__name__ == "__main__"): approach.

Here is a question highlighting how this works.

So, for your problem, you could do:

if (__name__ == "__main__"):
  logging.basicConfig(
      format="(%(levelname)s) %(module)22s :  %(message)s",
      datefmt="%m/%d/%Y %I:%M:%S %p",
      level=logging.INFO,
  )
log = logging.getLogger(__name__)

This means the root configuration will run only if the module is called directly.

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