/dev/null as a file-like object, or logging to nothing

Carsten Haese carsten at uniqsys.com
Sat Sep 8 13:28:10 EDT 2007


On Sat, 2007-09-08 at 18:52 +0200, Torsten Bronger wrote:
> Hallöchen!
> 
> Is there a portable and simply way to direct file-like IO to simply
> nothing?  I try to implement some sort of NullLogging by saying
> 
> --8<---------------cut here---------------start------------->8---
> import logging
> if options.logging:
>     logging.basicConfig(level=logging.DEBUG, filename=options.logfile, filemode="w",
>                         format='%(asctime)s %(name)s %(levelname)s   %(message)s')
> else:
>     # redirect logging to a memory buffer in order to simply ignore it.
>     import StringIO
>     logging.basicConfig(stream=StringIO.StringIO())
> --8<---------------cut here---------------end--------------->8---
> 
> However, this consumes memory.  Is there a better way?

This might work:

class LogSink(object):
    def write(self, *args, **kwargs): pass
    def flush(self, *args, **kwargs): pass

logging.basicConfig(stream=LogSink())

I haven't tested this thoroughly, so it's possible that there are more
methods that the stream is expected to implement.

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list