python中不同级别的日志记录

编程入门 行业动态 更新时间:2024-10-27 00:29:13
本文介绍了python中不同级别的日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想做一些我认为简单的事情.

I want to do something which I thought is simple.

实际上,我对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?)

这是目前设置我的日志记录系统的代码:

This is the code which sets up my logging system at the moment:

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)

推荐答案

这是我在所有Python命令行应用程序中使用的东西.这有点冗长,但是您应该能够获得一个接受可选参数的记录器,以在任何级别创建控制台记录器,而不管记录到文件中的内容是什么:

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')

从命令行运行时,我们可以看到已记录级别的差异.

Whenrun from the command line we can see the differences in logged levels.

-c1等于"DEBUG及更高版本"(最详细),但company.log仍仅记录警告和更高版本:

-c1 equates to "DEBUG and higher" (the most verbose), but company.log is still only logging WARNING and higher:

~ 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

-c20等于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

更多推荐

python中不同级别的日志记录

本文发布于:2023-07-16 16:13:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1123444.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中不   日志   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!