When is logging.getLogger(__name__) needed?

Peter Otten __peter__ at web.de
Fri Mar 31 11:34:31 EDT 2023


On 31/03/2023 15:01, Loris Bennett wrote:
> 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'.

Take another look at your code -- you'll probably find

>    logger = logging.getLogger(__name__)

on the module level in my_class.py.

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

Your problem has nothing to do with logging -- it's about visibility
("scope") of names:

 >>> def use_name():
	print(name)


 >>> def define_name():
	name = "Loris"


 >>> use_name()
Traceback (most recent call last):
   File "<pyshell#56>", line 1, in <module>
     use_name()
   File "<pyshell#52>", line 2, in use_name
     print(name)
NameError: name 'name' is not defined

Binding (=assigning to) a name inside a function makes it local to that
function. If you want a global (module-level) name you have to say so:

 >>> def define_name():
	global name
	name = "Peter"


 >>> define_name()
 >>> use_name()
Peter



More information about the Python-list mailing list