I have a Bar class which is a subclass of Foo
The Foo class contains the following
from game.utils import *
Here is game.utils
logger = logging.getLogger('myapp')
# create stream handler
stream_handler = logging.StreamHandler()
# create formatter
formatter = logging.Formatter('%(levelname)s - %(module)s - %(message)s')
# add formatter to stream handler
# add stream_handler to logger
Instance of the Foo class are logging correctly using the correct module name. However, when I create an instance of the Bar class, they are also logging using Foo’s module name. Is there something I can do to have those instances log using the module name of ‘bar’ rather than ‘foo’?
The module is the module where the log call is from, I’m guessing your log messages are coming from something that Bar has inherited from Foo, meaning that the code exists in the module where Foo is defined. I don’t see why you’d want to change that.
(Using Bar.stuff is to be logging from Foo’s module, that’s where stuff is defined)
Anyway, pure guesswork since your example is incomplete.
Also, not sure that importing all the names from games.util into your other module is wise. (Generally avoid
from module import * unless you’ve got a really good argument for why it’s needed or makes sense) – you might mean:
from games.util import logger which explicitly says what name to bring in, and avoids surprises when you add more names to games.util
Thanks for the tip about limiting the import to logger (rather than *). I’ve already made the changes and can see why it’s a smarter way to go.
You are correct that logs are being generated via the Foo class (from the foo module). The entire reason I’m subclassing the Bar class (from Foo) is for logging. In other words, using the log formatter described above, instances of the Bar class should generate logs such as: INFO - bar - this is the message
If I can’t do this, then there’s no point in creating the subclass at all since it really offers no other benefit.
The module field for the formatter thingymajig is where it was called from. There’s documentation available saying this. You’re after some other information, like the module where the type of the object is located. That’s something you can dig out of your object.
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.