English 中文(简体)
图1
原标题:Different levels of logging in python

我想做我认为很简单的事情。

Actually with the python logging module, I am interested logging everything on the command line at the level given from the command line arguments, and log to file to a fixed DEBUG level.

Creating two different loggers with different levels doesn t work, but setting the levels of two different handlers both added to the root logger doesn t work either, so any idea about how I should actually do it? (reading on other links the second approach should work, so am I doing something else stupid?)

这是目前建立我的伐木系统的法典:

class LoggerSetup(object):
    """Setup the different logger objects
    """

    def __init__(self):
        self.root_logger = logging.getLogger()
        self.shell_hdlr = logging.StreamHandler()

    #TODO: add another logging handler which stores to a temporary file
    #which should be cleaned up later
    def setup_shell_logger(self, log_level):
        self.root_logger.setLevel(LOG_LEVELS[log_level])
        # in this way the root logger is not set but the handlers are set
        self.shell_hdlr = logging.StreamHandler()
        self.shell_hdlr.setLevel(LOG_LEVELS[log_level])
        self.shell_hdlr.setFormatter(StarFormatter())
        #FIXME: add the support for regular expression exclusion too
        self.root_logger.addHandler(self.shell_hdlr)

    def setup_log_include(self, log_include):
        """Set up the filter to include log messages
        """
        if log_include:
            incl = FilterInclude(log_include)
            self.shell_hdlr.addFilter(incl)

    def setup_log_exclude(self, log_exclude):
        """Set up the filters to exclude log messages
        """
        if log_exclude:
            excl = FilterExclude(log_exclude)
            self.shell_hdlr.addFilter(excl)

    def setup_file_logging(self):
        """Set up the file logger, which always logs in DEBUG mode
        even if the top level logger is set to another level
        """
        #XXX: not working, one possible way to make it work is to create
        #only one log, and different handler/filters to make to handle all
        #the different outputs
        file_handler = logging.FileHandler(LOG_FILENAME)
        # the file logging is always in debug mode
        file_handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter( %(name)-12s: %(levelname)-8s %(message)s - %(asctime)s )
        file_handler.setFormatter(formatter)
        self.root_logger.addHandler(file_handler)
最佳回答

This is something I m using with all of my Python command-line apps. It s a little verbose, but you should be able to get a logger that accepts an optional argument to create a console logger at any level, irrespective of what s being logged to the file:

#!/usr/bin/env python
import logging
from argparse import ArgumentParser

COMPANY_LOGGER =  COMPANY.Python.Logger 
CONSL_LEVEL_RANGE = range(0, 51)
LOG_FILE =  company.log 
FORMAT_STR =  %(asctime)s %(levelname)s %(message)s 

parser = ArgumentParser()
parser.add_argument( -c ,  --console-log , metavar= ARG ,
                    type=int, choices=range(0, 51),
                    action= store , dest= console_log ,
                    default=None,
                    help= Adds a console logger for the level specified in the range 1..50 )

args = parser.parse_args()

# Create logger
logger = logging.getLogger(COMPANY_LOGGER)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(FORMAT_STR)

# Add FileHandler and only log WARNING and higher
fh = logging.FileHandler(LOG_FILE)
fh.name =  File Logger 
fh.level = logging.WARNING
fh.formatter = formatter
logger.addHandler(fh)

# Add optional ConsoleHandler
if args.console_log:
    ch = logging.StreamHandler()
    ch.name =  Console Logger 
    ch.level = args.console_log
    ch.formatter = formatter
    logger.addHandler(ch)

logger.debug( DEBUG )
logger.info( INFO )
logger.warning( WARNING )
logger.critical( CRITICAL )

从指挥线开始,我们就可以看到gged积层的差异。

-c1 equates to “DEBUG and high” (the most verbose), but corporate. 伐木率仍然高于伐木:

~ zacharyyoung$ ./so.py -c1
2012-01-12 08:59:50,086 DEBUG DEBUG
2012-01-12 08:59:50,086 INFO INFO
2012-01-12 08:59:50,087 WARNING WARNING
2012-01-12 08:59:50,087 CRITICAL CRITICAL

~ zacharyyoung$ cat company.log 
2012-01-12 08:59:50,087 WARNING WARNING
2012-01-12 08:59:50,087 CRITICAL CRITICAL

e 等同于INFO:

~ zacharyyoung$ ./so.py -c20
2012-01-12 09:00:09,393 INFO INFO
2012-01-12 09:00:09,393 WARNING WARNING
2012-01-12 09:00:09,393 CRITICAL CRITICAL

~ zacharyyoung$ cat company.log 
2012-01-12 08:59:50,087 WARNING WARNING
2012-01-12 08:59:50,087 CRITICAL CRITICAL
2012-01-12 09:00:09,393 WARNING WARNING
2012-01-12 09:00:09,393 CRITICAL CRITICAL
问题回答

暂无回答




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签