1

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

4

1 に答える 1