Example of how to use logging for both screen and file

Carlos Ribeiro carribeiro at gmail.com
Fri Oct 22 10:15:22 EDT 2004


On 22 Oct 2004 15:26:18 +0300, Ville Vainio <ville at spammers.com> wrote:
> Just posting this for the sake of google:
> 
> Like everyone else, I figured it's time to start using the 'logging'
> module.
> 
> I typically want to dump "info" level (and up) log information to
> screen, and "debug" level (and up) to a log file for in-depth
> analysis. This is for scripts, so date/time/severity information is
> not wanted. I assumed such a simple use case would have an example in
> the docs (py 2.4), but no luck.
> 
> Here's what worked for me:
> 
> import logging
> 
> def setupLogging():
>     global log
>     log = logging.getLogger("myapp")
>     log.setLevel(logging.DEBUG)
>     sth = logging.StreamHandler()
>     sth.setLevel(logging.INFO)
>     log.addHandler(sth)
>     fhnd = logging.FileHandler('/tmp/myapp.log')
>     fhnd.setLevel(logging.DEBUG)
>     log.addHandler(fhnd)
> 
> setupLogging()
> 
> log.info("foo")  # appears on screen and file
> log.debug("bar") # appears in the file only
> 
> The example might not be ideal, but something like this should really
> be in the module documentation. The example config file mostly serves
> to intimidate would-be users ("I need to do *that*?!?), and many of
> them probably wouldn't want to introduce a third-party wrapper module
> either (I think that should be the point of the standard logging
> module after all).

I'm also beginning to get to grips with the logging module. My first
attempt was confusing, and I ended up removing it from the code. Now I
just have a simple log method that still calls print <message>. Not
exactly what I wanted to do :-P

My idea now is to write a clean and simple wrapper for the logging
module, using sensible defaults, and exposing simple methods.
Something like (still pseudo-code):

from simplelog import Logger

log = Logger(<logger-name>)
...
log.info(<msg>)
log.debug(<msg>)
log.warning(<msg>)
log.error(<msg>, exception=<optional-exception-object>)

It's a simple implementation that hides a lot of the options of the
standard logging module. Messages would be automatically written to
the most appropriate output channels, using sensible defaults. That is
more than enough for most of my logging needs. It's still in the
drawing board, though.


-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list