| Andrew Cooke | Contents | Latest | RSS | Twitter | Previous | Next


Welcome to my blog, which was once a mailing list of the same name and is still generated by mail. Please reply via the "comment" links.

Always interested in offers/projects/new ideas. Eclectic experience in fields like: numerical computing; Python web; Java enterprise; functional languages; GPGPU; SQL databases; etc. Based in Santiago, Chile; telecommute worldwide. CV; email.

Personal Projects

Lepl parser for Python.

Colorless Green.

Photography around Santiago.

SVG experiment.

Professional Portfolio

Calibration of seismometers.

Data access via web services.

Cache rewrite.

Extending OpenSSH.

C-ORM: docs, API.

Last 100 entries

Weeks 10 + 11; Change: No Longer Possible To Merge Metadata; Books on Old Age; Health Tree Maps; MRA - Men's Rights Activists; Writing Good C++14; Risk Assessment - Fukushima; The Future of Advertising and Surveillance; Travelling With Betaferon; I think I know what I dislike so much about Metafilter; Weeks 8 + 9; More; Pastamore - Bad Italian in Vitacura; History Books; Iraq + The (UK) Governing Elite; Answering Some Hard Questions; Pinochet: The Dictator's Shadow; An Outsider's Guide To Julia Packages; Nobody gives a shit; Lepton Decay Irregularity; An Easier Way; Julia's BinDeps (aka How To Install Cairo); Good Example Of Good Police Work (And Anonymity Being Hard); Best Santiago Burgers; Also; Michael Emmerich (Vibrator Translator) Interview (Japanese Books); Clarice Lispector (Brazillian Writer); Books On Evolution; Looks like Ara (Modular Phone) is dead; Index - Translations From Chile; More Emotion in Chilean Wines; Week 7; Aeon Magazine (Science-ish); QM, Deutsch, Constructor Theory; Interesting Talk Transcripts; Interesting Suggestion Of Election Fraud; "Hard" Books; Articles or Papers on depolarizing the US; Textbook for "QM as complex probabilities"; SFO Get Libor Trader (14 years); Why Are There Still So Many Jobs?; Navier Stokes Incomplete; More on Benford; FBI Claimed Vandalism; Architectural Tessellation; Also: Go, Blake's 7; Delusions of Gender (book); Crypto AG DID work with NSA / GCHQ; UNUMS (Universal Number Format); MOOCs (Massive Open Online Courses); Interesting Looking Game; Euler's Theorem for Polynomials; Weeks 3-6; Reddit Comment; Differential Cryptanalysis For Dummies; Japanese Graphic Design; Books To Be Re-Read; And Today I Learned Bugs Need Clear Examples; Factoring a 67 bit prime in your head; Islamic Geometric Art; Useful Julia Backtraces from Tasks; Nothing, however, is lost with less discomfort than that which, when lost, cannot be missed; Article on Didion; Cost of Living by City; British Slavery; Derrida on Metaphor; African SciFi; Traits in Julia; Alternative Japanese Lit; Pulic Key as Address (Snow); Why Information Grows; The Blindness Of The Chilean Elite; Some Victoriagate Links; This Is Why I Left StackOverflow; New TLS Implementation; Maths for Physicists; How I Am 8; 1000 Word Philosophy; Cyberpunk Reading List; Detailed Discussion of Message Dispatch in ParserCombinator Library for Julia; FizzBuzz in Julia w Dependent Types; kokko - Design Shop in Osaka; Summary of Greece, Currently; LLVM and GPUs; See Also; Schoolgirl Groyps (Maths); Japanese Lit; Another Example - Modular Arithmetic; Music from United; Python 2 and 3 compatible alternative.; Read Agatha Christie for the Plot; A Constructive Look at TempleOS; Music Thread w Many Recommendations; Fixed Version; A Useful Julia Macro To Define Equality And Hash; k3b cdrom access, OpenSuse 13.1; Week 2; From outside, the UK looks less than stellar; Huge Fonts in VirtualBox; Keen - Complex Emergencies; The Fallen of World War II

© 2006-2015 Andrew Cooke (site) / post authors (content).

Logging in Python

From: "andrew cooke" <andrew@...>

Date: Sat, 26 Apr 2008 10:49:29 -0400 (CLT)

There's hardly any docs about this (apart from the way over-detailed
no-wood-for-the-trees library docs), but it turns out Python does have a
good (but broken!) logging system.

Motivated by my experience with Java logging I want:
- An external config that lets me control the level and location of messages
- Logging that is identified with modules, for easy filtering
  (module level is simpler than class level - see below - except that
  it tickles a bug, apparently)

And this is how I do it:

When the app starts, it calls

import logging
import logging.config
import sys
from acooke.util.path import sys_path_find
def init_log(name):
        path = sys_path_find(name)
        log = logging.getLogger(__name__)
        log.info('Configured logging from %s' % path)
        logging.exception('Failed to start logging: %s: %s'
                          % sys.exc_info()[:2])
        logging.warning('Will use default logging configuration')
        logging.warning('To fix this, put configuration in %s on $PYTHONPATH'
                        % name)

where sys_path_find runs through the system path looking for the named
file.  This loads the config, which is then accessed within modules as:

from acooke.util.log import Log
log = Log(__name__)

class Foo(object):
    def foo(self):
        log.debug("My debug message")

Which generates a log message associated with the module name.  You would
expect this to look like:

import logging
log = logging.getLoger(__name__)

but that doesn't work.  Instead, the Log class above lazily resolves the
logger instance so that creation happens *after* the configuration
described above has occurred.

class Log(object):
    def __init__(self, name):
        super(Log, self).__init__()
        self._name = name
        self._lazy = None
    def __getattr__(self, key):
        if not self._lazy:
            self._lazy = logging.getLogger(self._name)
        return getattr(self._lazy, key)

And finally, here's a typical config.  I send everything to the same
handler (syserr) with the same format, but i define three different
loggers.  One handles everything from modules in the "dbmac.*" tree (the
application), another handles modules in the "acooke.*" tree (libraries)
and a thrird is a catch all for anything else ("root" is a reserved name).




# configure level for system logs (if any) here

# configure level for main application here

# configure level for acooke libraries here


format=%(asctime)s [%(levelname)9s %(name)-30s] %(message)s

Typical log output looks like:

2008-04-26 08:54:44,209 [     INFO acooke.util.log               ]
Configured logging from
2008-04-26 08:54:49,224 [    DEBUG acooke.wx.validators          ] Engine
:= 789
2008-04-26 08:54:49,224 [    DEBUG acooke.wx.validators          ] Name :=


Comment on this post