473,471 Members | 2,613 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

python logging module problem

import os, sys, logging

logger = logging.getLogger("my_app")

conerr = logging.StreamHandler(sys.stderr)
conerr.setLevel(logging.DEBUG)
conerr_formatter = logging.Formatter('%(levelname)s %(message)s')
conerr.setFormatter(conerr_formatter)

console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.INFO)
console_formatter = logging.Formatter('%(message)s')
console.setFormatter(console_formatter)

logger.addHandler(conerr)
logger.addHandler(console)

logger.info("Ritesh Raj Sarraf.\n")
logger.warning("Ricky Raj Sarraf.\n")

Hi,

When I execute the above code, logger.info()'s messages don't get
displayed. And logger.warning()'s messages get displayed twice.

C:\Eclipse\Workspace\Python Fun>python log.py
WARNING Ricky Raj Sarraf.

Ricky Raj Sarraf.
Is there something I am doing wrong ?
I basically want to use Python's logging module for my entire program.
I want is something like logger.message() which would contain normal
program messages which shouldbe passed to stdout.

I also want to implement a logger.verbose() handler which would execute
when we enable verbose mode.

Am I doing it the correct way ? Or am I using the wrong tool ? Should
logging be used for it ?

TIA,
Ritesh

Jul 13 '06 #1
5 6061
Ritesh Raj Sarraf wrote:
import os, sys, logging

logger = logging.getLogger("my_app")

I tried this code:

import logging, sys

# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s
%(message)s',
stream=sys.stderr)

# define a Handler which writes INFO messages or higher to the
sys.stderr
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
#logging.getLogger('').addHandler(console)
logging.RootLogger(console)#.addHandler(console)

# Now, we can log to the root logger, or any other logger. First the
root...
logging.info('Jackdaws love my big sphinx of quartz.')
logging.debug('Ritesh raj Sarraf.\n')
With this it seems to be working halfway.
logging.debug() works perfect. But logging.info() is inheriting the
settings of logging.debug(). For example it is using logging.debug()'s
formatter while displaying. :-(

Ritesh

Jul 13 '06 #2
Ritesh Raj Sarraf wrote:
When I execute the above code, logger.info()'s messages don't get
displayed. And logger.warning()'s messages get displayed twice.
The warning messages are displayed twice because you have two handlers
which both output to the console.

The reason you don't get the info messages is that you haven't set a
level on the logger, so the default of WARNING is used.

It's usual to rely on logger levels and to set handler levels for
additional refinement of what goes to a particular handler's
destination.

Regards,

Vinay Sajip

Jul 14 '06 #3

Vinay Sajip wrote:
>
It's usual to rely on logger levels and to set handler levels for
additional refinement of what goes to a particular handler's
destination.
The problem is that for StreamHandler, logging module logs to
sys.stderr.
I want to use the logging feature for most of the messages my program
displays.

So some messages would be going to sys.stdout and some to sys.stderr.

So, I'm ended up creating two handlers, one for sys.stdout and the
other for sys.stderr.
I'd then make INFO level messages go to sys.stdout and DEBUG level
messages go to sys.stderr.

What do you suggest ??
Is it good doing this way ?

Ritesh

Jul 14 '06 #4
Ritesh Raj Sarraf wrote:
Vinay Sajip wrote:
>It's usual to rely on logger levels and to set handler levels for
additional refinement of what goes to a particular handler's
destination.
The problem is that for StreamHandler, logging module logs to
sys.stderr.
I want to use the logging feature for most of the messages my program
displays.

So some messages would be going to sys.stdout and some to sys.stderr.

So, I'm ended up creating two handlers, one for sys.stdout and the
other for sys.stderr.
I'd then make INFO level messages go to sys.stdout and DEBUG level
messages go to sys.stderr.

What do you suggest ??
Is it good doing this way ?
You can achieve the desired behaviour by adding a custom Filter:

import sys
import logging

logger = logging.getLogger("my_app")
logger.setLevel(logging.DEBUG)

class LevelFilter(logging.Filter):
def __init__(self, level):
self.level = level
def filter(self, record):
return self.level == record.levelno

def make_handler(outstream, format, level):
handler = logging.StreamHandler(outstream)
formatter = logging.Formatter(format)
handler.setFormatter(formatter)
handler.addFilter(LevelFilter(level))
return handler

logger.addHandler(make_handler(sys.stderr,
'STDERR %(levelname)s %(message)s', logging.WARN))
logger.addHandler(make_handler(sys.stdout,
'STDOUT %(levelname)s %(message)s', logging.INFO))

logger.info("the world is flat")
logger.warning("take care not to fall off its rim")

Not sure whether this is a good idea. Another way might be to use distinct
loggers.

Peter
Jul 14 '06 #5

Peter Otten wrote:
You can achieve the desired behaviour by adding a custom Filter:

import sys
import logging

logger = logging.getLogger("my_app")
logger.setLevel(logging.DEBUG)

class LevelFilter(logging.Filter):
def __init__(self, level):
self.level = level
def filter(self, record):
return self.level == record.levelno

def make_handler(outstream, format, level):
handler = logging.StreamHandler(outstream)
formatter = logging.Formatter(format)
handler.setFormatter(formatter)
handler.addFilter(LevelFilter(level))
return handler

logger.addHandler(make_handler(sys.stderr,
'STDERR %(levelname)s %(message)s', logging.WARN))
logger.addHandler(make_handler(sys.stdout,
'STDOUT %(levelname)s %(message)s', logging.INFO))

logger.info("the world is flat")
logger.warning("take care not to fall off its rim")

Not sure whether this is a good idea. Another way might be to use distinct
loggers.

Peter
Thanks. This looks similar to what I wanted. I'll try customizing it to
my requirements and see if this helps.

Thanks,
Ritesh

Jul 14 '06 #6

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

Similar topics

3
by: Frantisek Fuka | last post by:
I am using the standard "logging" module included with Python and it seems it doesn't correctly identify the filename (and thus module name) from where the logging method was called. In fact, no...
0
by: Kurt B. Kaiser | last post by:
Patch / Bug Summary ___________________ Patches : 378 open ( +3) / 3298 closed (+34) / 3676 total (+37) Bugs : 886 open (-24) / 5926 closed (+75) / 6812 total (+51) RFE : 224 open...
0
by: Karlo Lozovina | last post by:
I've just upgraded to Python 2.5, SQLAlchemy 0.3.3, and py2exe 0.6.5 (the py2.5 version, yes). Simple: --- import sqlalchemy print 'Test' ---
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
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,...
0
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...
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,...
0
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...
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
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...
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.