logging from severl classes

F

flupke

Hi,

i'm trying to log to the same file (using logging module) from different
classes but i can't seem to get it to work.
File 1 is the main file which sets up the logger and then i want to also
use the same logger in another class
This is what i have

file1
=============================
import logging

class A:
def __init__(self):
self.logger = logging.getLogger("app_logfile")
### stdout handler ###
self.logger.setLevel(logging.DEBUG)

stream_hld = logging.StreamHandler()
stream_hld.setLevel(logging.DEBUG)
stream_formatter =
logging.Formatter('%(asctime)s %(levelname)s %(module)s %(lineno)d
%(message)s ')
stream_hld.setFormatter(stream_formatter)
self.logger.addHandler(stream_hld)")
=============================

file2
=============================
import logging

class B:
def __init__(self):
self.logger = logging.getLogger("app_logfile")
self.logger.debug("creating class B")

def otherfunction(self):
self.logger.debug("in otherfunction")
=============================

But i get an error:
AttributeError: B instance has no attribute 'logger'

I was hoping that by requesting a logger with the same name
(app_logfile) i would get the setup also and could use the logger
straight away. Funny thing is that the use of the logger in the __init__
function of class B works but the call to the logger in otherfunction
doesn't work and results in the error above.
Class B is created after class A so the logger object exists already.

Any ideas of what i'm doing wrong and how i can achieve setting up the
logger object only once?

Thanks,
Benedict
 
V

Vinay Sajip

It works for me:

#file3.py
import file1
import file2

a = file1.A()
b = file2.B()
b.otherfunction()

gives

2004-12-28 00:18:34,805 DEBUG file2 6 creating class B
2004-12-28 00:18:34,805 DEBUG file2 9 in otherfunction
 
F

flupke

Vinay said:
It works for me:

#file3.py
import file1
import file2

a = file1.A()
b = file2.B()
b.otherfunction()

gives

2004-12-28 00:18:34,805 DEBUG file2 6 creating class B
2004-12-28 00:18:34,805 DEBUG file2 9 in otherfunction

yeah, the classes where a simplification of the classes i'm using and
used these to just show what i wanted to do without testing them.
they indeed work. strange.
Thanks for your answer

benedict
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,167
Latest member
SusanaSwan
Top