Friday, September 03, 2010

A Standard Way to Use Python's Logging Module

The documentation for Python's logging module shows you its great features, but it doesn't mention standard usage if you are writing a little application or a library.

Make a separate logger for each file, and name the loggers to match the hierarchy of modules. For the file acert/hfesr/, it starts with:

import logging
logger = logging.getLogger('acert.hfesr.Runner')
class Runner(object):
def __init__(self):
logger.debug('Initializing Runner')

That's quite simple. Then you can enable and disable logging by file or by module.

The second tip is that, if you have written a library, don't use logging.basicConfig() in that library because it makes logging handlers that are difficult for subsequent client applications to quiet.


/dev/null for C++ ostream

I often make C++ classes that write to some stream given to them:

Bear::Save(std::ostream& out) {
out << "Fur is " << color << std::endl;
out << "Age is " << age << std::endl;

Editing somebody's code today, I needed an ostream equivalent of /dev/null, some stream into which a class could write without printing anything. This can be done by creating a stream buffer that never prints.

class nullbuf : public std::basic_streambuf
virtual int overflow(int c) { return c; }

class nullstream : public std::basic_ostream > {
nullbuf _streambuf;
nullstream() :
std::basic_ostream &gt(&_streambuf)
{ clear(); }


Using it looks like any other stream:

nullstream dev_null;
dev_null << "Nobody will ever see this.";
ostream* output = new nullstream();
(*output) << "This will be invisible.";

As usual, hope this helps.