-1

I have a python module and I want to set a logger to be available through the package.

  1. I initiate the logger in the __init__.py
  2. run the code with python -m
  3. call a function in another file which needs logger from __init__.py

then I ger this error

name 'logger' is not defined

__init__.py:

import logging
logging.basicConfig(format='%(msg)s')
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

from .code import log
log()

code.py:

def log():
    logger.debug('test')
  • How (if at all) do you try to get the logger from `__init__.py` to where you're using it? Give a [mre] rather than a description. – jonrsharpe Sep 28 '20 at 08:32
  • @jonrsharpe thank you I added example . When I imported log and also I'm in a module which should have global variable I expect log function be able to see the logger. – Erfan Ghofrani Sep 28 '20 at 09:04
  • *"I'm in a module which should have global variable"* - I'm not sure why you think that, that's **not** what defining it in `__init__.py` does. – jonrsharpe Sep 28 '20 at 09:05
  • Oh so how should i make a variable or function accessible through the module ? or i have to initiate the logger in every file of module ? – Erfan Ghofrani Sep 28 '20 at 09:07
  • See e.g. https://stackoverflow.com/q/22282316/3001761, https://stackoverflow.com/q/1201115/3001761 – jonrsharpe Sep 28 '20 at 09:10

1 Answers1

0

special thank to @jonrsharpe linked me to Python: How to import from an __init__.py file?

the solution for having a logger object through the module and don't initiate it in every file is :

from . import logger