473,769 Members | 5,757 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

logging module example

Hola, pythonisas:
The documentation for the logging module is good, but a bit obscure.
In particular, there seems to be a lot of action at a distance.
The fact that getLogger() can actually be a call to Logger.__init__ (),
which is mentioned in para 6.29.1, also bears stressing on 6.29. I
grasp _why_ you'd implement it that way, but I may not be the only
coder who feels queasy with the word 'get' being used both to fetch
an instance and to trigger instantiation.
Anyway, after poring over the documentation, unit test, and source code,
I'd like to show a sample script that will eventually be used
in my vanity project, with four loggers of increasing granularity.
I realize there are probably more ways to do this (logging seemingly
sporting perl-esque flexibility ;) so please weigh in with thoughts.
Perhaps now I can go back and get this to work with the
logging.config interface. :)
Best,
Chris

#----begin log_test.py------------------
import logging

#Set up a hierarchy such that we have:
#root - everything, including function arguments
#`trunk - function calls
# `branch - application state
# `leaf - externally visible actions

forest = ["root","trunk", "branch","l eaf"]
#relate our logger names to levels
lumber_jack = {forest[0] : logging.DEBUG
,forest[1] : logging.INFO
,forest[2] : logging.WARNING
,forest[3] : logging.ERROR }
#Used to build up the log names into a hierarchy
log_name = []

for log in forest:
mounty = logging.FileHan dler("%s%s.txt" % ("/home/smitty/mddl/",log))
log_name.append (log)
print "Instantiat ing %s" % ".".join(log_na me)
timber = logging.getLogg er(".".join(log _name))
timber.setLevel (lumber_jack[log])
timber.addHandl er(mounty)
if lumber_jack[log] == logging.DEBUG:
timber.debug( "%s's a lumberjack, and he's OK." % log)
elif lumber_jack[log] == logging.INFO:
timber.info( "%s's a lumberjack, and he's OK." % log)
elif lumber_jack[log] == logging.WARNING :
timber.warning( "%s's a lumberjack, and he's OK." % log)
elif lumber_jack[log] == logging.ERROR:
timber.error( "%s's a lumberjack, and he's OK." % log)

#Force a logging event from the handler for the current logger.
# This hanlder event short-circuits the up-stream propogation
# of the log record, as seen in the file outputs.
mounty.emit( logging.LogReco rd( timber
, 0
, "/mnt/dmz/proj/mddl4/mddl.py"
, 37
, "burp?"
, None
, None ))

#----end log_test.py------------------

#--------
#output:
#--------
Instantiating root
Instantiating root.trunk
Instantiating root.trunk.bran ch
Instantiating root.trunk.bran ch.leaf

#-------
#The four files:
#-------
$cat root.txt
root's a lumberjack, and he's OK.
burp?
trunk's a lumberjack, and he's OK.
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.

$cat trunk.txt
trunk's a lumberjack, and he's OK.
burp?
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.

$cat branch.txt
branch's a lumberjack, and he's OK.
burp?
leaf's a lumberjack, and he's OK.

$cat leaf.txt
leaf's a lumberjack, and he's OK.
burp?
Dec 31 '05 #1
3 2468
Chris Smith schrieb:
Hola, pythonisas:
The documentation for the logging module is good, but a bit obscure.
In particular, there seems to be a lot of action at a distance.
The fact that getLogger() can actually be a call to Logger.__init__ (),
which is mentioned in para 6.29.1, also bears stressing on 6.29. I
grasp _why_ you'd implement it that way, but I may not be the only
coder who feels queasy with the word 'get' being used both to fetch
an instance and to trigger instantiation.
The reason for this "distance" is simply that you should be able to get
a grip on a logger from wherever you are, explicitly _without_ first
having to instantiate it and possibly pass it around. Think of this
little example:

class Mixin(object):
def foo(self):
logger = logging.getLogg er("MixinLogger ")
logger.debug("I 'm foo!")

def bar(self):
logger = logging.getLogg er("MixinLogger ")
logger.debug("I 'm bar!")

class User(Mixin):

def some_random_met hod(self):
if relative_moon_h umidity() > .8:
self.foo()
else:
self.bar()
So the decoupling makes lots of sense in logging IMHO.
Anyway, after poring over the documentation, unit test, and source code,
I'd like to show a sample script that will eventually be used
in my vanity project, with four loggers of increasing granularity.
I realize there are probably more ways to do this (logging seemingly
sporting perl-esque flexibility ;) so please weigh in with thoughts.
Perhaps now I can go back and get this to work with the
logging.config interface. :) forest = ["root","trunk", "branch","l eaf"]
#relate our logger names to levels
lumber_jack = {forest[0] : logging.DEBUG
,forest[1] : logging.INFO
,forest[2] : logging.WARNING
,forest[3] : logging.ERROR }
#Used to build up the log names into a hierarchy
log_name = []

for log in forest:
mounty = logging.FileHan dler("%s%s.txt" % ("/home/smitty/mddl/",log))
log_name.append (log)
print "Instantiat ing %s" % ".".join(log_na me)
timber = logging.getLogg er(".".join(log _name))
timber.setLevel (lumber_jack[log])
timber.addHandl er(mounty)
if lumber_jack[log] == logging.DEBUG:
timber.debug( "%s's a lumberjack, and he's OK." % log)
elif lumber_jack[log] == logging.INFO:
timber.info( "%s's a lumberjack, and he's OK." % log)
elif lumber_jack[log] == logging.WARNING :
timber.warning( "%s's a lumberjack, and he's OK." % log)
elif lumber_jack[log] == logging.ERROR:


That looks as an misunderstandin g or somewhat strange usage of the
logging-api. It is _very_ uncommon to have loggers level depending on
_data_. Instead you just invoke

logger.debug(so me_data)

and set the level elsewhere. That is a somewhat static rleationship -
all forests are supposed to share _one_ logging instance, with it's
current log-level. And you don't check for the level being DEBUG or
whatever. You just log, and if the level is above (or below, whatever
stance you take) the currently set level for that logger, the message
gets displayed.

All in all it seems that you have some difficulties with the loggers
being a sort of global objects. Keep that in mind when developing using
them.

Regards,

Diez
Dec 31 '05 #2
>>>>> "Diez" == Diez B Roggisch <de***@nospam.w eb.de> writes:

Diez> Chris Smith schrieb:
Hola, pythonisas: The documentation for the logging module is
good, but a bit obscure. In particular, there seems to be a
lot of action at a distance. The fact that getLogger() can
actually be a call to Logger.__init__ (), which is mentioned in
para 6.29.1, also bears stressing on 6.29. I grasp _why_ you'd
implement it that way, but I may not be the only coder who
feels queasy with the word 'get' being used both to fetch an
instance and to trigger instantiation.
Diez> The reason for this "distance" is simply that you should be
Diez> able to get a grip on a logger from wherever you are,
Diez> explicitly _without_ first having to instantiate it and
Diez> possibly pass it around. Think of this little example:

[snip]

Diez> So the decoupling makes lots of sense in logging IMHO.

Absolutely. The fact that it does eventually make sense, however, doesn't
preclude a bout of confusion at the fact that some_lager didn't
already exist before

pint = logging.getLogg er( some_lager )

and that the logging module will merrily brew some_lager on the spot.
I submit that the documentation might be improved by including your
example on 6.29, gearing the neophyte up for how this (can we agree it
operates on slightly different principles than most?) module operates.

Anyway, after poring over the documentation, unit test, and
source code, I'd like to show a sample script that will
eventually be used in my vanity project, with four loggers of
increasing granularity. I realize there are probably more ways
to do this (logging seemingly sporting perl-esque flexibility
;) so please weigh in with thoughts. Perhaps now I can go back
and get this to work with the logging.config interface. :)


[snip]

Diez> That looks as an misunderstandin g or somewhat strange usage
Diez> of the logging-api. It is _very_ uncommon to have loggers
Diez> level depending on _data_. Instead you just invoke

Diez> logger.debug(so me_data)

Diez> and set the level elsewhere. That is a somewhat static
Diez> releationship - all forests are supposed to share _one_
Diez> logging instance, with it's current log-level. And you don't
Diez> check for the level being DEBUG or whatever. You just log,
Diez> and if the level is above (or below, whatever stance you
Diez> take) the currently set level for that logger, the message
Diez> gets displayed.

My use-case is a desire to interpret an input file, and log traces at
varying output depth. I used the default labels, just to keep the
sample script small. However, I will (once I have grokked
that corner of the module more fully) follow your advice there, for
I'm really only talking about four densities of debug information.
Thank you for this feedback.

Diez> All in all it seems that you have some difficulties with the
Diez> loggers being a sort of global objects. Keep that in mind
Diez> when developing using them.

Yep, got to play the tune sloppy a few times before it's tight.
Nochmals vielen Dank. :)
Chris

Jan 1 '06 #3
One thing that made little sense to me when I was first working on
this is the following variation on the original script:

#--begin test script--
import logging

forest = ["root","trunk", "branch","l eaf"]
lumber_jack = {forest[0] : logging.DEBUG
,forest[1] : logging.INFO
,forest[2] : logging.WARNING
,forest[3] : logging.ERROR }
log_name = []
for log in forest:
mounty = logging.FileHan dler("%s%s.txt" % ("/home/smitty/mddl/",log))
log_name.append (log)
print "Instantiat ing %s" % ".".join(log_na me)
timber = logging.getLogg er(".".join(log _name))

#Comment out explit setting of level for logger
#timber.setLeve l(lumber_jack[log])

#Commented out totally, called without argument, or called with
# logging.NOTSET all produce same output

#timber.setLeve l(logging.NOTSE T)
timber.addHandl er(mounty)
if lumber_jack[log] == logging.DEBUG:
timber.debug( "%s's a lumberjack, and he's OK." % log)
elif lumber_jack[log] == logging.INFO:
timber.info( "%s's a lumberjack, and he's OK." % log)
elif lumber_jack[log] == logging.WARNING :
timber.warning( "%s's a lumberjack, and he's OK." % log)
elif lumber_jack[log] == logging.ERROR:
timber.error( "%s's a lumberjack, and he's OK." % log)
mounty.emit( logging.LogReco rd( timber
, 0
, "/mnt/dmz/proj/mddl4/mddl.py"
, 37
, "burp?"
, None
, None ))
#--end test script--

#---
#expected output
#---
$ cat root.txt
root's a lumberjack, and he's OK.
burp?
trunk's a lumberjack, and he's OK.
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.
$ cat trunk.txt
trunk's a lumberjack, and he's OK.
burp?
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.
$ cat branch.txt
branch's a lumberjack, and he's OK.
burp?
leaf's a lumberjack, and he's OK.
$ cat leaf.txt
leaf's a lumberjack, and he's OK.
burp?
#---
#actual output
#---
$ cat root.txt
burp?
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.
$ cat trunk.txt
burp?
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.
$ cat branch.txt
branch's a lumberjack, and he's OK.
burp?
leaf's a lumberjack, and he's OK.
$ cat leaf.txt
leaf's a lumberjack, and he's OK.
burp?
#-------
At any rate, I see now that I want to use logging.setLeve l() to lay
in my own, more descriptive, levels, and then the straight
logging.log() function to do that for me.
Ah, the learning curve.
Best,
Chris
Jan 1 '06 #4

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

Similar topics

6
10883
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
1744
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
2224
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
1543
by: Leo Breebaart | last post by:
I have another question where I am not so much looking for a solution but rather hoping to get some feedback on *which* solutions people here consider good Pythonic ways to approach a issue. The situation is this: I am writing fairly large console scripts in Python. They have quite a few command-line options, which lead to configuration variables that are needed all over the program (e.g. the "--verbose" option alone is used by just...
0
1864
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: >...
3
1606
by: seb | last post by:
Hi, I am writing to a file some basic information using the logging module. It is working but in the log file some line are printed several time. I had put some print debugging messages in the logging function (so they appear on the consile) and they are called once only. Obviously there is some understantding of the logging module that I am missing. My simple logging program (see below) is called by several processes. In this way I...
4
3332
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
6423
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:
1
1942
by: ludvig.ericson | last post by:
Quote from the docs: FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s" logging.basicConfig(format=FORMAT) d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} logging.warning("Protocol problem: %s", "connection reset", extra=d) would print something like
0
9423
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,...
0
10039
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9990
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
9860
tracyyun
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...
0
8869
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...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5297
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...
0
5445
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3560
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.