Making `logging.basicConfig` log to *both* `sys.stderr` and `sys.stdout`?

Daniel Dehennin daniel.dehennin at ac-dijon.fr
Tue Oct 23 07:04:21 EDT 2012


Hello,

>> Unfortunately this setup makes `logging.basicConfig` pretty useless.
>> However, I believe that this is something that more people could
>> benefit from. I also believe, that it just "makes sense" to send
>> warnings (and above) to `stderr`, the rest to `stdout`.

[...]

> Python 2.x is closed to feature changes, and Python 2.7 and Python 3.2
> already support flexible configuration using dictConfig() - see
> 
> http://docs.python.org/library/logging.config.html#logging.config.dictConfig
> 
> Also, Python 3.3 will support passing a list of handlers to
> basicConfig(): see
> 
> http://plumberjack.blogspot.com/2011/04/added-functionality-for-basicconfig=
> -in.html
> 
> which will allow you to do what you want quite easily.

I tried to setup the same for my scripts with
"logging.config.dictConfig()" without much success, I want to limit
output to stdout to INFO, everything bellow INFO should be sent to
stderr instead.

Any hints?

Here is my configuration:

#+begin_src python
def init_logging(options):
    # TODO: color stderr messages by level if sys.stderr.isatty()
    config = { 'version' : 1,
               'formatters' : { 'stdout' : { 'format' : '%(message)s',
                                             'datefmt' : '', },
                                'stderr' : { 'format' : '%(message)s',
                                             'datefmt' : '', },
                },
               'handlers' : { 'stdout' : { 'class' : 'logging.StreamHandler',
                                           'stream' : 'ext://sys.stdout',
                                           'level' : 'INFO',
                                           'formatter' : 'stdout', },
                              'stderr' : { 'class' : 'logging.StreamHandler', 
                                           'stream' : 'ext://sys.stderr',
                                           'level' : 'WARNING', 
                                           'formatter' : 'stderr', }
                },
               'root' : { 'level' : options.log_level.upper(),
                          'handlers' : ['stdout', 'stderr'],
                },
    }

    logging.config.dictConfig( config )
    return logging.getLogger()
#+end_src

Regards.
-- 
Daniel Dehennin
EOLE
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 229 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20121023/e02d8a02/attachment.sig>


More information about the Python-list mailing list