如何自定义python记录器行为?

时间:2018-12-17 16:59:41

标签: python python-3.x logging stdout

我已经实现了我的其他python类使用的custom_logger。

import logging, sys

logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
    datefmt='%d-%m-%Y:%H:%M:%S',

logger = logging.getLogger()

我将按以下方式使用它:

import custom_logger as cl
cl.logger.debug('Extracting locations and descriptors from %s' % image_path)

我正在从脚本中运行python文件,在该脚本中,我尝试将日志记录重定向到sout和serr的其他文件中

nohup python3  "$CLASSPATH""$MAIN_CLASS" $MAIN_CLASS_ARGUMENT 1>>$SOUT_FILE 2>>$SERR_FILE & echo $! > $PID_FILE

使用当前设置,我将在.err文件中获取所有日志

  

17-12-2018:17:56:59,203 INFO [conn.py:1008]设置配置   api_version = {0,11,0)在启动时跳过自动check_version请求   17-12-2018:17:56:59,206 INFO [subscription_state.py:172]正在更新   订阅了以下主题:('PROCESSED_SCENES',)17-12-2018:17:56:59,209   INFO [cluster.py:342] my_group的组协调器是   BrokerMetadata(nodeId = 0,host ='172.1.1.3',port = 9094,rack = None)

我尝试调整记录器以在每个文件中输出错误,但没有成功:

import logging, sys

class StdErrFilter(logging.Filter):
    def filter(self, rec):
        return rec.levelno in (logging.ERROR, logging.WARNING)

class StdOutFilter(logging.Filter):
    def filter(self, rec):
        return rec.levelno in (logging.DEBUG, logging.INFO)

logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
    datefmt='%d-%m-%Y:%H:%M:%S',
    level=logging.INFO)

formatter = logging.Formatter('%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s','%d-%m-%Y:%H:%M:%S')

logger = logging.getLogger()


h1 = logging.StreamHandler(sys.stdout)
h1.setFormatter(formatter)
h1.addFilter(StdOutFilter())
logger.addHandler(h1)

h2 = logging.StreamHandler(sys.stderr)
h2.setFormatter(formatter)
h2.addFilter(StdErrFilter())
logger.addHandler(h2)

我现在得到的只是两个.err .out文件中的输出相同。

我想念什么?

1 个答案:

答案 0 :(得分:1)

basicConfig配置一个处理程序,因此您拥有h1h2和基本日志记录。也许这会引起混乱?另外,您还需要为记录器执行logger.setLevel(logging.DEBUG),以完全处理调试级别。

删除basicConfig并添加setLevel似乎可以达到预期目的:

import logging, sys

class StdErrFilter(logging.Filter):
    def filter(self, rec):
        return rec.levelno in (logging.ERROR, logging.WARNING)

class StdOutFilter(logging.Filter):
    def filter(self, rec):
        return rec.levelno in (logging.DEBUG, logging.INFO)

formatter = logging.Formatter('%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s','%d-%m-%Y:%H:%M:%S')
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

h1 = logging.StreamHandler(sys.stdout)
h1.setFormatter(formatter)
h1.addFilter(StdOutFilter())
logger.addHandler(h1)

h2 = logging.StreamHandler(sys.stderr)
h2.setFormatter(formatter)
h2.addFilter(StdErrFilter())
logger.addHandler(h2)

logger.info('stdout log')
logger.error('stderr log')