473,604 Members | 2,483 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

logging module: add client_addr to all log records


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|in ternal]: Unable to Pronounce 'ni!'
[WARNING|2006-05-08 23:44:57,421|fr ench.knights.nu]: Incoming Bovine

I'm grateful for any advice.

/Joel Hedlund

import logging
import cowlogger
logger = logging.getLogg er('cowlogger')
logger.warning( "Unable to Pronounce 'ni!'")
logger.warning( "Incoming Bovine Detected",
client_addr = 'french.knights .nu')

import logging

BaseLogger = logging.getLogg erClass()

class LogRecord(loggi ng.LogRecord):
def __init__(self, name, level, pathname, lineno, msg, args,
exc_info, client_addr):
Adding client_addr as instantiation parameter and
logging.LogReco rd.__init__(sel f, name, level, pathname,
lineno, msg, args, exc_info)
self.client_add r = client_addr

class CowLogger(BaseL ogger):
def makeRecord(self , name, level, fn, lno, msg, args, exc_info,
Code nicked from logging.Logger. I just added client_addr
to header and LogRecord instantiation.
return LogRecord(name, level, fn, lno, msg, args, exc_info,

def _log(self, level, msg, args, exc_info=None,
client_addr = 'internal'):
Code nicked from logging.Logger. I just added client_addr
to header and makeRecord call.
if logging._srcfil e:
fn, lno, func = self.findCaller ()
fn, lno, func = "(unknown file)", 0, "(unknown function)"
if exc_info:
if type(exc_info) != types.TupleType :
exc_info = sys.exc_info()
record = self.makeRecord (self.name, level, fn, lno, msg,
args, exc_info, client_addr)
self.handle(rec ord)

logging.setLogg erClass(CowLogg er)

# Setting up log item formatting:
format = "[%(levelname)s|% (asctime)s|%(cl ient_addr)s]: %(message)s"
formatter = logging.Formatt er(format)
handler = logging.StreamH andler()
handler.setForm atter(formatter )
logger = logging.getLogg er('cowlogger')
logger.addHandl er(handler)

May 8 '06 #1
1 2256
> See a very similar example which uses the new 'extra' keyword argument:

Now that's brilliant! Exactly what I need.

But unfortunately, it's also unavailable until 2.5 comes out. Until then I'm
afraid I'm stuck with my shoddy hack... but it's always nice to know the time
will come when I can finally throw it out!

Thanks for taking the time!

May 11 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Kamus of Kadizhar | last post by:
Does anyone have a working example or a recipe of a simple logging system using the logging module? Any FM I can refer to? I can't seem to get it right - I can't even make sense of the standard library docs. What do I have to do to log records to a file? (Newbie Q, as you might guess...) -Kamus
by: Robert.Schmitt | last post by:
I found that the configuration system of the new logging package of Python 2.3 has some unintuitive idiosyncracies that are worth mentioning because they can cost you quite some development time and are not documented elsewhere. I used the logging configuration file shown below. My aim was to log only the INFO messages, but log DEBUG messages for one particular module (called webTestLogin.py).
by: Ville Vainio | last post by:
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.
by: rh0dium | last post by:
Hi all, So I have a slice of code which calls other python code. I have started to take a real liking to the logging module, but I want to extend this into the called python code. I have no idea how to pass the handle from the calling code into the modules.. So basically here is what I do.. -- Main Program --
by: Rotem | last post by:
Hi, while working on something in my current project I have made several improvements to the logging package in Python, two of them are worth mentioning: 1. addition of a logging record field %(function)s, which results in the name of the entity which logged the record. My version even deduces the class name in the case which the logger is a bound method, and assuming the name of the "self" variable is indeed "self".
by: Jed Parsons | last post by:
Hi, I'm using the logging module for the first time. I'm using it from within Zope Extensions. My problem is that, for every event logged, the logger is producing multiple identical entries with the timestamp the same down to the millisecond. Is this something I'm doing wrong?
by: robert | last post by:
As more and more python packages are starting to use the bloomy (Java-ish) 'logging' module in a mood of responsibility and as I am not overly happy with the current "thickener" style of usage, I want to put this comment and a alternative most simple default framework for discussion. Maybe there are more Python users which like to see that imported (managed) logging issue more down-to-earth and flexible ? ... Vinay Sajip wrote: >...
by: Frank Aune | last post by:
Hello, I've been playing with the python logging module lately, and I manage to log to both stderr and MySQL database. What I'm wondering, is if its possible to specify the database handler in a config file like: class=DBHandler
by: Lowell Alleman | last post by:
Here is the situation: I wrote my own log handler class (derived from logging.Handler) and I want to be able to use it from a logging config file, that is, a config file loaded with the logging.config.fileConfig() function. Let say my logging class is called "MyLogHandler" and it's in a module called "mylogmodule", I want to be able to make an entry something like this in my logging config file:
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.