-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')
5
  • How (if at all) do you try to get the logger from __init__.py to where you're using it? Give a minimal reproducible example rather than a description. Commented Sep 28, 2020 at 8: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. Commented Sep 28, 2020 at 9: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. Commented Sep 28, 2020 at 9: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 ? Commented Sep 28, 2020 at 9:07
  • See e.g. stackoverflow.com/q/22282316/3001761, stackoverflow.com/q/1201115/3001761 Commented Sep 28, 2020 at 9:10

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.