how to use logging module to log an object like print()

bieffe62 at gmail.com bieffe62 at gmail.com
Wed Oct 29 11:53:01 EDT 2008


On 29 Ott, 12:24, Steve Holden <st... at holdenweb.com> wrote:
> Diez B. Roggisch wrote:
> > davy zhang schrieb:
> >> mport logging
> >> import pickle
>
> >> # create logger
> >> logger = logging.getLogger("simple_example")
> >> logger.setLevel(logging.DEBUG)
> >> # create console handler and set level to debug
> >> ch = logging.StreamHandler()
> >> ch.setLevel(logging.DEBUG)
> >> # create formatter
> >> formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
> >> - %(message)s ")
> >> # add formatter to ch
> >> ch.setFormatter(formatter)
> >> # add ch to logger
> >> logger.addHandler(ch)
>
> >> d = {'key':'msg','key2':'msg2'}
>
> >> # "application" code
> >> logger.debug("debug message",d)#can not do this
>
> > logger.debug("yes you can: %r", d)
>
> One deficiency of this approach, however, is that the string formatting
> is performed even when no logging is required, thereby wasting a certain
> amount of effort on unnecessary formatting.
>
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/- Nascondi testo citato
>

Sure about that?

This is the implementation of Logger.debug in
the file : ..Python25\lib\logging\__init__.py

   def debug(self, msg, *args, **kwargs):
        """
        Log 'msg % args' with severity 'DEBUG'.

        To pass exception information, use the keyword argument
exc_info with
        a true value, e.g.

        logger.debug("Houston, we have a %s", "thorny problem",
exc_info=1)
        """
        if self.manager.disable >= DEBUG:
            return
        if DEBUG >= self.getEffectiveLevel():
            apply(self._log, (DEBUG, msg, args), kwargs)


The other methods (info, warning, ...) are similar. It looks like
the formatting is only done if actually used.

Ciao
-----
FB



More information about the Python-list mailing list