Logging to different addressees

Vinay Sajip vinay_sajip at yahoo.co.uk
Wed Jul 16 01:21:52 CEST 2008


On Jul 15, 5:17 pm, McA <andreas.m... at web.de> wrote:
> > If you added the admin sink handler to the root logger, you're done.
>
> Isn't that the first thing above? What do you mean?

I gave you a choice - to add the handler to the admin_logger OR the
root logger. So I am saying here that if you added to the root logger
(and not common_logger, assuming they're different), then there's
nothing more to do...
>
> > Otherwise, you need to ensure that certain_logger is a child of
> > common_logger.
>
> What I want to code is something like that.
> a) I know thet this is a message for the admin only:
> admin_logger.log('blabla')  (admin_logger = root_logger =logging.get_logger(""))
>
> b) certain_logger.log('something'  => log to the root/admin/-sink as
> well as to the
> certain-sink.
>
> Do I have to create a logger subclass where I do the multiplexing of
> theloggingmessages?
> I'm pretty sure I miss something. ;-)
>

No, the logging package is designed to allow flexibility of different
events being logged to different destinations. There's no need to
subclass Logger to achieve what you're asking for. The following
script:

# simple.py
import logging

admin_logger = logging.getLogger("") # The root logger
addressee_logger = logging.getLogger("addressee")

admin_sink = logging.FileHandler("admin.log", "w")
addressee_sink = logging.FileHandler("addressee.log", "w")

admin_logger.addHandler(admin_sink)
addressee_logger.addHandler(addressee_sink)

admin_logger.setLevel(logging.DEBUG)

admin_logger.debug("This message appears in admin sink only.")
addressee_logger.debug("This message appears in both admin sink and
addressee sink."

# - end of simple.py

Generates the following results:

----------------------------------------------------------
admin.log
----------------------------------------------------------
This message appears in admin sink only.
This message appears in both admin sink and addressee sink.

----------------------------------------------------------
addressee.log
----------------------------------------------------------
This message appears in both admin sink and addressee sink.

Regards,

Vinay Sajip



More information about the Python-list mailing list