Python记录多个文件

时间:2012-02-29 13:37:18

标签: python logging

我的Python日志模块有问题,我不确定我是否在这里做了一些愚蠢的事情,但我有两个Python脚本,一个(master.py)调用另一个(slave.py)。它们都记录到单独的日志文件,但被调用的第二个脚本(slave.py)似乎递归地记录!

谁能看到我在这里做错了什么?

这是我的代码:

# master.py

import sys
import logging
import slave

masterLog = logging.getLogger('master')
masterLog.setLevel(logging.DEBUG)
masterHandler = logging.FileHandler('master.log')
formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
masterHandler.setFormatter(formatter)
masterLog.addHandler(masterHandler)
masterLog.info('This is masterLog running on master.py')
print 'master.py has: ', len(masterLog.handlers), 'handlers'

for i in range(1,6):
      masterLog.info('Running slave %s' % i)
      slave.runMain()

# slave.py

import sys
import logging

def runMain():
    slaveLog = logging.getLogger('slave')
    slaveLog.setLevel(logging.DEBUG)
    slaveHandler = logging.FileHandler('slave.log')
    formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
    slaveHandler.setFormatter(formatter)
    slaveLog.addHandler(slaveHandler)
    slaveLog.info('This is slaveLog running on slave.py')
    print 'slave.py has: ', len(slaveLog.handlers), 'handlers'

if __name__ == '__main__':
    runMain()

这是输出:

master.py has:  1 handlers
slave.py has:  1 handlers
slave.py has:  2 handlers
slave.py has:  3 handlers
slave.py has:  4 handlers
slave.py has:  5 handlers

还有master.log:

INFO: 2012-02-29 13:26:49 <module>(13) -- This is masterLog running on master.py
INFO: 2012-02-29 13:26:49 <module>(17) -- Running slave 1
INFO: 2012-02-29 13:26:49 <module>(17) -- Running slave 2
INFO: 2012-02-29 13:26:49 <module>(17) -- Running slave 3
INFO: 2012-02-29 13:26:49 <module>(17) -- Running slave 4
INFO: 2012-02-29 13:26:49 <module>(17) -- Running slave 5

slave.log:

INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py
INFO: 2012-02-29 13:26:49 runMain(13) -- This is slaveLog running on slave.py

每次调用时,slave脚本似乎都会添加一个新文件Handler。 slave.log文件中应该只有5个条目,但每次调用slave.py时,logger输出到每个文件处理程序!

谢谢, JAK

2 个答案:

答案 0 :(得分:5)

logging.getLogger([name])总是返回相同的对象(全局对象),每次调用runMain时都会在其上调用addHandler。

答案 1 :(得分:0)

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import logging.handlers
from logging.config import dictConfig

logger = logging.getLogger(__name__)

DEFAULT_LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
}
def configure_logging(logfile_path):
    """
    Initialize logging defaults for Project.

    :param logfile_path: logfile used to the logfile
    :type logfile_path: string

    This function does:

    - Assign INFO and DEBUG level to logger file handler and console handler

    """
    dictConfig(DEFAULT_LOGGING)

    default_formatter = logging.Formatter(
        "[%(asctime)s] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] [PID:%(process)d TID:%(thread)d] %(message)s",
        "%d/%m/%Y %H:%M:%S")

    file_handler = logging.handlers.RotatingFileHandler(logfile_path, maxBytes=10485760,backupCount=300, encoding='utf-8')
    file_handler.setLevel(logging.INFO)

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)

    file_handler.setFormatter(default_formatter)
    console_handler.setFormatter(default_formatter)

    logging.root.setLevel(logging.DEBUG)
    logging.root.addHandler(file_handler)
    logging.root.addHandler(console_handler)



[31/10/2015 22:00:33] [DEBUG] [yourmodulename] [yourfunction_name():9] [PID:61314 TID:140735248744448] this is logger infomation from hello module

我认为你最好在main函数中配置日志格式。