473,657 Members | 2,458 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

logging module: add client_addr to all log records

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

I'm grateful for any advice.

Cheers!
/Joel Hedlund

test.py
---------------------------------------------------------------------
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')
---------------------------------------------------------------------

cowlogger.py
---------------------------------------------------------------------
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
attribute.
"""
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,
client_addr):
"""
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,
client_addr)

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 ()
else:
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 2263
> 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!

Cheers!
/Joel
May 11 '06 #2

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

Similar topics

5
1263
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
0
1655
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).
6
10872
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.
2
1738
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 --
23
2210
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".
7
2418
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?
0
1856
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: >...
4
3325
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
3
6418
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:
0
8420
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8324
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,...
1
8516
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,...
0
7353
agi2029
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...
0
5642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2743
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
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
bsmnconsultancy
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.