Creating multiple loggers in Python to different outputs in the same module

时间:2016-04-26 14:18:11

标签: python python-2.7 logging

So I want to create multiple loggers in the same module

log = logging.getLogger('FirstLogger')
plog = logging.getLogger('SecondLogger')

and I want to configure each logger separately.

so I added a FileHandler for plog that only takes logging.INFO or above while the FileHandler for log would take logging.DEBUG or above.

I have created an init_logger() function that takes in the instance of the logger to perform the configuration on

def init_logger(logger, fmode, cmode)

So i want FirstLogger to log to a file that i created separately for it and log with DEBUG level. I would do

log = logging.getLogger('FirstLogger')
init_logger(log,logging.DEBUG,logging.INFO)

plog = logging.getLogger('SecondLogger')
init_logger(plog,logging.INFO,logging.INFO)

In init_logger I specify different files for the FileHandler and set the levels according to what is passed to init_logger.

flog = logging.FileHandler(logfile)
flog.setLevel(fmode)
flog.setFormatter(...)

console = logging.StreamHandler()
console.setLevel(cmode)
console.setFormatter(...)

log.addhandler(flog)
log.addHandler(console)

The problem I have is that even though 'log' has console set level to INFO and the FileHandler to DEBUG I still only get INFO in both the file and the console. I can't figure out what is wrong with what I am doing.

1 个答案:

答案 0 :(得分:1)

您将文件处理程序的级别设置为DEBUG,但是您没有将记录器本身的级别设置为DEBUG

log.setLevel(min(cmode, fmode))