473,587 Members | 2,501 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

logging module and threading

I would like my different threads to log without stepping on each
other.

Past advice on this list (that I've found) mostly says to send the
messages to a Queue. That would work, but bypasses the logging
module's facilities.

The logging module itself is "thread-safe", but I think that just
means that individual output is protected. If I have, in temporarly
sequence:
thread 1: warning("A")
thread 2: info("something ")
thread 1: warning("B")
then I think I'll get them output in this order. It's thread-safe in
that the log will not end up with an entry like
A
some
B
thing
(I think). But I want to get, for example,
A
B
something

What I would like is for each thread to emit a chunk of log messages
when it finishes a unit of work.

It looks as if I might be able to use a MemoryHandler to accumulate
the log locally and then flush it into the main log (I'd like to send
it to the main logger, but it looks as if I must send it to a specific
handler). Would something like the following work?

class MyThread (threading.Thre ad):
def __init__(self):
# do I need the next line?
threading.Threa d.__init__(self )
self._log = logging.getLogg er(self.getName ())
# flush into main log
self._log = logging.MemoryH andler(9999999,
, # default flushlevel
logging.getLogg er().handlers[1] )

def run(self):
j = getjob()
while j:
# do stuff
# log like this
self._log.info( "some message")
# when done
self._log.flush ()
j = getjob()
I'm also puzzled by how the logger hierarchy works. The docs say that
everything that is logged by the kids is also logged by the parent.
That would seem to defeat what I'm trying to do above, since the
parent would get each logged event right away. However,
logging.getLogg er("a").error(" test")
produces only a single log message indicating an associated object of "a".
The docs lead me to expect that I'd see one message from "a" and
another from root.

When I add handlers (e.g., FileHandlers) I do get the message recorded
by each.

Can anyone explain what's going on?

Thanks.
Ross Boylan

May 12 '07 #1
3 4285
On May 12, 1:53 am, Ross Boylan <r...@biostat.u csf.eduwrote:
>
I'm also puzzled by how the logger hierarchy works. The docs say that
everything that is logged by the kids is also logged by the parent.
That would seem to defeat what I'm trying to do above, since the
parent would get each logged event right away. However,logging .getLogger("a") .error("test")
produces only a single log message indicating an associated object of "a".
The docs lead me to expect that I'd see one message from "a" and
another from root.

When I add handlers (e.g., FileHandlers) I do get the message recorded
by each.

Can anyone explain what's going on?
The Logger hierarchy works, in a nutshell, as follows: events passed
to a logger propagate up the hierarchy until either the root, or a
logger whose propagate attribute is set to a false value, is reached.
At each step (i.e. logger) in the propagation, any handlers attached
to that logger are offered the chance to handle the message - which
means different things depending on the handler. If you add e.g. a
FileHandler to the root logger and another to a logger named "a.b.c"
and then log something to "a.b.c", then two handlers will each handle
the message, leading to multiple output of the same event. You also
don't need to buffer up messages in different threads - if your
messages contain both the log event time and the thread id (which can
be achieved by having %(asctime)s or %(relativeCreat ed)d and %
(thread)d or %(threadName)s in your format string), then you can
simply sort the output to group your messages together. (And since
threads sometimes interact, it's often useful to see the raw output in
time order.) If you do want to buffer events, MemoryHandler will do
the trick. And it takes a target handler rather than logger, because
it's acting as a buffer for another handler, for events which have
already been entered into the system.

If you're new to logging, you need to separate the ideas behind
loggers and handlers in the scheme of things. Loggers are things which
application developers use to register events of interest in their
application, with an indication of importance (level) and an ability
to filter on that. Handlers are things used by developers or admins to
send information about the events to different audiences - e.g.
critical errors might be emailed to someone while less critical errors
are sent to console or log files.

Best regards,

Vinay Sajip

May 12 '07 #2
Ross Boylan <ro**@biostat.u csf.eduwrote:
I would like my different threads to log without stepping on each
other.
Past advice on this list (that I've found) mostly says to send the
messages to a Queue. That would work, but bypasses the logging
module's facilities.
The logging module itself is "thread-safe", but I think that just
means that individual output is protected. If I have, in temporarly
sequence:
thread 1: warning("A")
thread 2: info("something ")
thread 1: warning("B")
then I think I'll get them output in this order. It's thread-safe in
that the log will not end up with an entry like
A
some
B
thing
(I think). But I want to get, for example,
A
B
something
What I would like is for each thread to emit a chunk of log messages
when it finishes a unit of work.

This sounds like a job for the Queue class/module to me.
Could you create a Queue such that all your worker threads
are producers to it and you have one dedicated thread as a
consumer that relays log entries from the Queue into your loggers?

--
Jim Dennis,
Starshine: Signed, Sealed, Delivered

Jun 13 '07 #3
On Jun 13, 1:28 am, "James T. Dennis" <jades...@idiom .comwrote:
This sounds like a job for the Queue class/module to me.
Could you create a Queue such that all your worker threads
are producers to it and you have one dedicated thread as a
consumer that relays log entries from the Queue into your loggers?
Or, use a SocketHandler to serialize the events over a socket, and de-
mux them on the receiving end. The docs have an example:

http://docs.python.org/lib/network-logging.html

Regards,

Vinay Sajip

Jun 13 '07 #4

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

Similar topics

6
10869
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...
1
1162
by: Roger | last post by:
I'd like to use a program (roundup) that imports the logging.config module on a machine where I could not get the thread and threading modules to compile. How dangerous is it to changing /lib/python2.4/logging/config.py to something like: import dummy_thread as thread, dummy_threading as threading
2
1735
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
2207
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...
1
1963
by: usenet | last post by:
I'm having some problems getting the logging module to work with the threading module. I've narrowed the problem down to the following code: import logging, threading update_log = logging.getLogger('update_log') update_log.addHandler(logging.FileHandler("/tmp/update_log")) class dlThread(threading.Thread):
0
1849
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...
4
3320
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
6409
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...
3
5737
by: scriptlearner | last post by:
I am trying to put up a queue (through a logging thread) so that all worker threads can ask it to log messages. However, the problem I am facing is that, well, the logging thread itself is running forever. It does not know when it should exit. Any suggestion? None of the worker threads knows for sure when the logging thread should exit...
0
7920
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...
0
7849
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...
0
8215
Oralloy
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. ...
0
8347
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...
0
8220
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...
1
5718
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...
0
3879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1454
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1189
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...

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.