程序执行多次,但无法正确更新日志文件

时间:2018-08-24 12:59:45

标签: python logging

该脚本的日志文件有点麻烦。当我启动脚本时,第一个日志文件将正确填充。没有问题。由于该脚本使用Rabbitmq并充当使用者,因此该脚本几乎可以连续运行。 (它将消息从队列中拉出,运行,然后等待重复)。问题是当脚本运行第二或第三次等时,日志文件与第一个测试相同,尽管该文件应该有所不同。

总而言之,我正在运行一些测试,并使用Rabbitmq将适当的测试分发给合适的消费者。使用者(带有此脚本的PC)在每次收到消息时都会运行。该代码的主要目的是执行一个工具(如nmap),然后打包结果。我假设问题可能出在我的记录器的设置方式上,因此对于那些阅读者来说,不要太着迷于该工具的功能。日志相关或shutil.copy可能是问题,但我不确定这是怎么回事。这是简化的代码。

import os
import subprocess
from ast import literal_eval
from datetime import datetime
import logging
import logging.config
import shutil
import zipfile
import yaml


TOOL = 'nmap'
LOGGER_NAME = 'nmap-Run'

logger = None


class Tool(object):
    ''' class for test execution'''

    def __init__(self):
        ToolDefault.__init__(self, tool=TOOL)

    def _execute_tool(self):
        ''' Execute test based on associated yaml'''

        logging.config.fileConfig('C:\\Users\\cschu\\Documents\\Sec\\src\\config\\test_log.conf')
        global logger
        logger = logging.getLogger(LOGGER_NAME)
        logger.info('Retrieving options')
        options = literal_eval(self.options)

        split_string = ['some', 'command', 'here']

        try:
            cmd_line_process = subprocess.Popen(split_string,
                                                stdout=subprocess.PIPE,
                                                stderr=subprocess.STDOUT)
            process_output, process_error = cmd_line_process.communicate()
            logger.info(process_output)
        except (OSError, subprocess.CalledProcessError) as e:
            logger.info('An exception occurred: ', str(e))
            logger.info('Test failed')

        else:
            logger.info('Test has concluded')

    def _package_report(self):
        ''' Find latest test results and zip into local directory folder results.zip

        '''

        logger.info('Finding most recent test results')

        # do some work in a directory here looking for latest file with strftime
        upload_path = r"C:\test\resultFolder"

        logger.debug('Most recent test result is ' + upload_path)
        try:
            shutil.copy(r'C:\Users\cschu\Documents\Sec\src\Logg.log', upload_path)
        except IOError as e:
            pass

        # do work to zip upload_path which has Logg.log copied to it 
        # zip folder is called results.zip in local dir
        return r'C:\Users\cschu\Documents\Sec\src\results.zip'


def main():
    ''' 
    Do some work with rabbitmq and run the test based off rabbitmq message. 
    '''
    tool_object = Tool()
    rabbit_connection = RabbitConnection(tool_object)
    rabbit_connection.start()


if __name__ == '__main__':
    main()

这是我的test_log.conf文件。

[loggers]
keys=root

[handlers]
keys=consoleHandler,fileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler,fileHandler

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=(os.getenv('LOG_FILE_PATH'), 'w')
# LOG_FILE_PATH is 'C:\Users\cschu\Documents\Sec\src\Logg.log'

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

几乎,将返回一个包含测试内容和日志文件的压缩文件夹。该日志文件应该与第一个测试始终相同,尽管它应该有所不同。有人看到我的脚本如何初始化配置文件或类似问题吗?我想这就是问题所在。

0 个答案:

没有答案