On 9/11/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I think the following question is clearer.
>
> I want to make it so that method1 below can be transformed:
>
> logger = logging.getLogger("somelogger")
> class SomeOp:
>     def __init__(self, ctx):
>         self.ctx = ctx
>     def method1(self):
>         logger.info("%s: here's a message", self.ctx)
>         logger.debug("%s: msg #2", self.ctx)
>         v = 'yessir'
>         logger.debug("%s: msg #3 %s", self.ctx, v)
>
> into something like:
>
>     def method1(self):
>         logger.info("here's a message")
>         logger.debug("msg #2")
>         v = 'yessir'
>         logger.debug("msg #3 %s", v)
>
>
> What is the best way to do this, so that I don't have to manually put
> the self.ctx in the log string in hundreds of different places?

One way to do it is to make a mixin class (eg: ContextLogging)  which
you construct with the context string. The mixin constructor has a
line like this:

self.logger = logging.getLogger(ctx).

(assuming your context string is appropriate for a logger name)

Then your methods call self.logger instead of the module-level logger.

Another method is also to use a mixin class, which provides methods
"log_debug", "log_info", etc methods which wrap calls to a logger
object.

Another (more advanced) method is to create a custom Logger class. It
uses the call stack to determine if it's caller has a "ctx" attribute,
and pushes the value of that attribute into the message string. Then
you call logging.setLoggerClass so that you get instances of your
custom logger class.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to