1

记录3.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()

第一个.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')

记录器.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 对象的日志信息在哪里?<---------------

另外,有人可以确认上面的日志树是


----first
---------foo

还是
root
----root.first
--------------root.first.foo

4

1 回答 1

1

这是故意的。记录器有一个日志级别(控制台和文件分开);你可以设置它们

foo.setConsoleLevel(logging.ERROR)
foo.setFileLevel(logging.INFO)

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

低于当前日志级别的日志消息将被抑制;只有当前级别或高于当前级别的消息才能通过。这意味着信息消息可以进入文件,但不能进入屏幕,或者您可以将级别更改为调试以在调试时获得额外的输出等。

于 2013-10-23T14:17:25.163 回答