logging module: add client_addr to all log records

Vinay Sajip vinay_sajip at yahoo.co.uk
Tue May 9 18:49:18 EDT 2006


Joel.Hedlund at gmail.com wrote:

> Hi!
>
> I'm writing a server and I want to use the logging module for logging
> stuff. I want to log all transactions in detail, and if everything goes
> haywire I want to know which client did it. Therefore I want to affix
> the client address to every single log item.
>
> I would like to do the following:
> Formatter("[%(client_addr)s]: %(message)s")
> ...
> logger.critical("Offal Barrage Detected: Running Away", client_addr =
> 'french.knights.org')
>
> I've written something that accomplishes this (example below), but I
> have this nagging feeling that this could have been done in a better
> way. Any ideas?
>
> When test.py executes it prints this:
> [WARNING|2006-05-08 23:44:57,421|internal]: Unable to Pronounce 'ni!'
> [WARNING|2006-05-08 23:44:57,421|french.knights.nu]: Incoming Bovine
> Detected
>
> I'm grateful for any advice.
>
> Cheers!
> /Joel Hedlund
>

See a very similar example which uses the new 'extra' keyword argument:

http://docs.python.org/dev/lib/module-logging.html

The example is for a similar use case to yours - showing the IP address
of a client in a logging message.

Best regards,

Vinay Sajip




More information about the Python-list mailing list