Question

Question about sharing 'functions' between classes.
Situation:

  • All my own code is in 1 file
  • I'm using python-daemon to daemonize my script
  • That uses a class (Doorcamdaemon) to initiate and run.
  • It imports another class (Doorcam) which has a looping function
  • I'm using a sample script for the daemon functions, and it shows how to use the logging module.

The logging works from the main part of the script and in the Doorcamdaemon class, but not in the Doorcam class.

class Doorcamdaemon():
    def __init__(self):
        #skipping some content, not related to this issue
        self.Doorcam=Doorcam()

    def run(self):
        self.Doorcam.startListening() #looping function

class Doorcam
    def __init__(self):
        #skipping somecontent, not related to this issue
    def startListening(self):
        while True:
            logger.info('Hello')

app = Doorcamdaemon()
logger = logging.getLogger("DoorcamLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.FileHandler("/var/log/doorcam.log")
handler.setFormatter(formatter)
logger.addHandler(handler)

daemon_runner = runner.DaemonRunner(app)
daemon_runner.daemon_context.files_preserve=[handler.stream]
daemon_runner.do_action()

The error returned is:

$ ./Doorcam.py start
Traceback (most recent call last):
  File "./Doorcam.py", line 211, in <module>
    app = Doorcamdaemon()
  File "./Doorcam.py", line 159, in __init__
    self.doorcam=Doorcam()
  File "./Doorcam.py", line 18, in __init__
    logger.info('Doorcam started capturing')
NameError: global name 'logger' is not defined

So my obvious question: How can I make it work in the Doorcam class as well?

Was it helpful?

Solution

Try moving the line

app = Doorcamdaemon()

to after the lines that create and set up logger. The traceback is telling you:

  1. logger doesn't exist in line 18 where Doorcam's constructor tries to use it

  2. Doorcamdaemon tries to construct a Doorcam at line 159 in its own constructor

So you can't create a Doorcamdaemon if logger isn't defined yet.

Some of the content you omitted in Doorcam.__init__ was related to this issue :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top