Python logging module: how to save log to a file i

2019-06-03 07:16发布

I am looking for an elegant and Pythonic solution, to make tests save a log to a file, though only in case of test failure. I would like to keep things simple, and stick with Python's built-in logging module.

My current solution is to use a wrapper function for assert of every test:

import unittest

class superTestCase(unittest.TestCase): 
    ...

    def assertWithLogging(self, assertion, assertion_arguments, expected_response, actual_response, *args):
        try:
            assertion(*assertion_arguments)
        except AssertionError as ae:
            test_name = inspect.stack()[1][3]
            current_date_time = datetime.datetime.now().strftime("%Y.%m.%d %H-%M-%S")
            logging.basicConfig(filename='tests/{}-{}-Failure.log'.format(current_date_time, test_name),
                                filemode='a',
                                format='%(message)s',
                                level=logging.DEBUG
                                )
            logger = logging.getLogger('FailureLogger')
            logger.debug('{} has failed'.format(test_name))
            logger.debug('Expected response(s):')
            logger.debug(expected_response)
            logger.debug('Actual response:')
            logger.debug(actual_response)
            for arg in args:
                logger.debug('Additionl logging info:')
                logger.debug(arg)
            raise ae

    def testSomething(self):
        ...

        self.assertWithLogging(self.assertEqual,
                               [expected_response, actual_response]
                               expected_response,
                               actual_response,
                               some_other_variable
                               )

Though it works as I expect it to, this solution seems clumsy and not too Pythonic, to me.

  1. What would be (Is there) a more elegant way to achieve the same result?
  2. What are the downsides of current approach?

1条回答
啃猪蹄的小仙女
2楼-- · 2019-06-03 07:56

You can use various logging mechanisms where in you can set the type of logs you want to achieve.

The one below will log only error messages.

Logger.error(msg, *args, **kwargs)

This logs msg with level logging.ERROR on this logger. The arguments are interpreted as for debug().

查看更多
登录 后发表回答