Python日志记录:未在终端上显示

时间:2013-10-21 18:21:38

标签: python

logging3.py

import sys
import logging
import first
import Logger

root = logging.getLogger()
root.addHandler(Logger.get_streamhandler())
root.warning('we did something in info')

hi = first.Foo()
hi.baz()

first.py

import logging

import Logger

first_logger = logging.getLogger(__name__)
first_logger.parent = False
first_logger.addHandler(Logger.get_streamhandler())
first_logger.info('in first')


class Foo:
    def __init__(self):
        print 'making sure we are in first.Foo' 
        self.logger = logging.getLogger('foo')
        self.logger.addHandler(Logger.get_streamhandler())
        self.logger.info('created Foo obj')
    def baz(self):
        self.logger.info('i dont know what baz is')

Logger.py

  1 import logging
  2 import sys
  3
  4
  5 '''
  6     NOTSET means inherit the log level from the parent logger
  7 '''
  8
  9 LEVELS = {  'debug'   : logging.DEBUG,
 10             'info'    : logging.INFO,
 11             'warning' : logging.WARNING,
 12             'error'   : logging.ERROR,
 13             'critical': logging.CRITICAL,
 14          }
 15
 16 def getLevel(lvl):
 17     return LEVELS.get(lvl) or logging.DEBUG
 18
 19 def get_streamhandler(lvl=None):
 20     sh =  logging.StreamHandler()
 21     fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
 22     sh.setFormatter(logging.Formatter(fmt))
 23     sh.setLevel(getLevel(lvl))
 24     return sh

输出:
python logging3.py

2013-10-21 14:18:09,687 - first - INFO - in first  
2013-10-21 14:18:09,687 - root - WARNING - we did something in info  
making sure we are in first.Foo  

Foo对象的日志信息在哪里? < ---------------

此外,有人可以确认上面的日志记录树是


----第一
--------- foo

或者是它 根
---- root.first
--------------root.first.foo

1 个答案:

答案 0 :(得分:1)

这是故意的。记录器有一个loglevel(控制台和文件分开);你可以用

设置它们
foo.setConsoleLevel(logging.ERROR)
foo.setFileLevel(logging.INFO)

等。如果您将loglevel更改为logging.INFO(在我的python 2.6会话中为0x14)或更低,那么您将看到日志消息。

禁止记录低于当前日志级别的消息;只传递当前级别或以上的消息。这意味着信息消息可以转到文件,但不能转到屏幕,或者您可以更改级别以进行调试,以便在调试时获得额外的输出等。