473,467 Members | 1,463 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

how to use logging module to log an object like print()

mport logging
import pickle
# create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
- %(message)s ")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)

d = {'key':'msg','key2':'msg2'}

# "application" code
logger.debug("debug message",d)#can not do this
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
Oct 29 '08 #1
10 1241
davy zhang schrieb:
mport logging
import pickle
# create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
- %(message)s ")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)

d = {'key':'msg','key2':'msg2'}

# "application" code
logger.debug("debug message",d)#can not do this
logger.debug("yes you can: %r", d)
Diez
Oct 29 '08 #2
thanks so much , I ganna check the formatter str for more info:)

On Wed, Oct 29, 2008 at 5:10 PM, Diez B. Roggisch <de***@nospam.web.dewrote:
davy zhang schrieb:
>>
mport logging
import pickle
# create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
- %(message)s ")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)

d = {'key':'msg','key2':'msg2'}

# "application" code
logger.debug("debug message",d)#can not do this

logger.debug("yes you can: %r", d)
Diez
--
http://mail.python.org/mailman/listinfo/python-list
Oct 29 '08 #3
Diez B. Roggisch wrote:
davy zhang schrieb:
>mport logging
import pickle
# create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
- %(message)s ")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)

d = {'key':'msg','key2':'msg2'}

# "application" code
logger.debug("debug message",d)#can not do this

logger.debug("yes you can: %r", d)
One deficiency of this approach, however, is that the string formatting
is performed even when no logging is required, thereby wasting a certain
amount of effort on unnecessary formatting.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Oct 29 '08 #4
On Oct 29, 11:24 am, Steve Holden <st...@holdenweb.comwrote:
>
One deficiency of this approach, however, is that the string formatting
is performed even when nologgingis required, thereby wasting a certain
amount of effort on unnecessary formatting.
Though you can mitigate this using the pattern:

if logger.isEnabledFor(logging.DEBUG):
logger.debug("Message with variable data which may be expensive:
%s", expensive_call())

Which will only make the expensive_call() and formatting when the
logging call will actually do something.

Regards,

Vinay Sajip
Oct 29 '08 #5
On 29 Ott, 12:24, Steve Holden <st...@holdenweb.comwrote:
Diez B. Roggisch wrote:
davy zhang schrieb:
mport logging
import pickle
# create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
- %(message)s ")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
d = {'key':'msg','key2':'msg2'}
# "application" code
logger.debug("debug message",d)#can not do this
logger.debug("yes you can: %r", d)

One deficiency of this approach, however, is that the string formatting
is performed even when no logging is required, thereby wasting a certain
amount of effort on unnecessary formatting.

regards
*Steve
--
Steve Holden * * * *+1 571 484 6266 * +1 800 494 3119
Holden Web LLC * * * * * * *http://www.holdenweb.com/- Nascondi testo citato
Sure about that?

This is the implementation of Logger.debug in
the file : ..Python25\lib\logging\__init__.py

def debug(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'DEBUG'.

To pass exception information, use the keyword argument
exc_info with
a true value, e.g.

logger.debug("Houston, we have a %s", "thorny problem",
exc_info=1)
"""
if self.manager.disable >= DEBUG:
return
if DEBUG >= self.getEffectiveLevel():
apply(self._log, (DEBUG, msg, args), kwargs)
The other methods (info, warning, ...) are similar. It looks like
the formatting is only done if actually used.

Ciao
-----
FB
Oct 29 '08 #6
Steve Holden schrieb:
Diez B. Roggisch wrote:
>davy zhang schrieb:
>>mport logging
import pickle
# create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
- %(message)s ")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)

d = {'key':'msg','key2':'msg2'}

# "application" code
logger.debug("debug message",d)#can not do this
logger.debug("yes you can: %r", d)
One deficiency of this approach, however, is that the string formatting
is performed even when no logging is required, thereby wasting a certain
amount of effort on unnecessary formatting.
Nope, it's not. It only happens when the message is really logged.

Diez
Oct 29 '08 #7
bi******@gmail.com wrote:
On 29 Ott, 12:24, Steve Holden <st...@holdenweb.comwrote:
>Diez B. Roggisch wrote:
>>davy zhang schrieb:
mport logging
import pickle
# create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
- %(message)s ")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
d = {'key':'msg','key2':'msg2'}
# "application" code
logger.debug("debug message",d)#can not do this
logger.debug("yes you can: %r", d)
One deficiency of this approach, however, is that the string formatting
is performed even when no logging is required, thereby wasting a certain
amount of effort on unnecessary formatting.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/- Nascondi testo citato

Sure about that?

This is the implementation of Logger.debug in
the file : ..Python25\lib\logging\__init__.py

def debug(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'DEBUG'.

To pass exception information, use the keyword argument
exc_info with
a true value, e.g.

logger.debug("Houston, we have a %s", "thorny problem",
exc_info=1)
"""
if self.manager.disable >= DEBUG:
return
if DEBUG >= self.getEffectiveLevel():
apply(self._log, (DEBUG, msg, args), kwargs)
The other methods (info, warning, ...) are similar. It looks like
the formatting is only done if actually used.
Pretty sure, and Vinay's reply convinced me I was correct. He should
know, after all ...

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Oct 30 '08 #8
Diez B. Roggisch wrote:
Steve Holden schrieb:
>Diez B. Roggisch wrote:
>>davy zhang schrieb:
mport logging
import pickle
# create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
- %(message)s ")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)

d = {'key':'msg','key2':'msg2'}

# "application" code
logger.debug("debug message",d)#can not do this
logger.debug("yes you can: %r", d)
One deficiency of this approach, however, is that the string formatting
is performed even when no logging is required, thereby wasting a certain
amount of effort on unnecessary formatting.

Nope, it's not. It only happens when the message is really logged.
Vinay, please tell me whether I was right or wrong ...

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Oct 30 '08 #9
Steve Holden <st***@holdenweb.comwrote:
>Diez B. Roggisch wrote:
>Steve Holden schrieb:
>>Diez B. Roggisch wrote:
davy zhang schrieb:
logger.debug("debug message",d)#can not do this

logger.debug("yes you can: %r", d)

One deficiency of this approach, however, is that the string formatting
is performed even when no logging is required, thereby wasting a certain
amount of effort on unnecessary formatting.

Nope, it's not. It only happens when the message is really logged.
Vinay, please tell me whether I was right or wrong ...
If you will forgive me for putting words into your mouth, Steve, I suspect
that you originally read the line as this:
logger.debug("yes you can: %r" % d)
instead of what was actually written:
logger.debug("yes you can: %r" , d)

With the %, of course the formatting will be done whether or not the string
is logged. With the comma, the string formatting is done inside the logger
module, and will be skipped if the message is not needed.

This is exactly why logger supports this somewhat unusual feature. Now,
one can certainly imagine circumstances where the parameter evaluation is
expensive, so Vinay's bypass is still useful in some circumstances.
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Oct 31 '08 #10
On Oct 30, 4:34 am, Steve Holden <st...@holdenweb.comwrote:
>
Vinay, please tell me whether I was right or wrong ...
What Tim Roberts has already said is right ... my post was
highlighting how to mitigate any overhead which is typically (or at
least in general terms) higher than the cost of formatting, viz. the
computation of the values which get formatted.

Regards,

Vinay Sajip
Oct 31 '08 #11

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

Similar topics

6
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...
10
by: Peter Mott | last post by:
I am using: Python 2.3.4 (#2, Nov 14 2004, 18:06:48) ] on freebsd4 with Apache/1.3.26. The following script causes an Internal Server Error (with nothing in the Apache error logs AFAIK): ...
8
by: qwweeeit | last post by:
Hi all, I wonder if it is possible to change (temporarily) a built-in function for logging purposes. Let me explain: I want to log all the 'open' operations, recording the file to be opened, the...
2
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...
3
by: Chris Smith | last post by:
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...
7
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...
1
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 =...
7
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. ...
3
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...
2
by: Russell Warren | last post by:
I was just setting up some logging in a make script and decided to give the built-in logging module a go, but I just found out that the base StreamHandler always puts a newline at the end of each...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
1
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...
0
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...
0
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,...
0
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.