When is logging.getLogger(__name__) needed?

Loris Bennett loris.bennett at fu-berlin.de
Fri Mar 31 09:01:27 EDT 2023


Hi,

In my top level program file, main.py, I have

  def main_function():

      parser = argparse.ArgumentParser(description="my prog")

      ...

      args = parser.parse_args()
      config = configparser.ConfigParser()

      if args.config_file is None:
          config_file = DEFAULT_CONFIG_FILE
      else:
          config_file = args.config_file

      config.read(config_file)

      logging.config.fileConfig(fname=config_file)
      logger = logging.getLogger(__name__)

      do_some_stuff()
      
      my_class_instance = myprog.MyClass()

  def do_some_stuff():

      logger.info("Doing stuff")

This does not work, because 'logger' is not known in the function
'do_some_stuff'.

However, if in 'my_prog/my_class.py' I have

  class MyClass:

      def __init__(self):

          logger.debug("created instance of MyClass")

this 'just works'.

I can add 

  logger = logging.getLogger(__name__)

to 'do_some_stuff', but why is this necessary in this case but not in
the class?

Or should I be doing this entirely differently?

Cheers,

Loris

-- 
This signature is currently under constuction.


More information about the Python-list mailing list