0

I am performing a simple Python Django TestCase. The question is simple: I want to use loggers to redirect information (stdout) to one file and failures/errors (stderr) to another.

I know I can print stdout to a file simply by defining the logger and using it to print the messages (i.e. logger.info('my debug message')); however, I have not found a way to log a failure/error. I can redirect the output of the entire test run using Bash (of which I am semi-successful), but I know there is a way to simplify it and use loggers to do all that backend work for me.

Here is an example of my logger:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s, %(module)s at line %(lineno)d:\n%(message)s'
        },
    },
    'handlers': {
        'app': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'logs/app.log',
            'formatter': 'verbose'
        },
        'test': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'logs/test.log',
            'formatter': 'verbose'
        },
        'test-fail': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': 'logs/test-fail.log',
            'formatter': 'verbose',
        }
    },
    'loggers': {
        'app': {
            'handlers': ['app'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'test': {
            'handlers': ['test', 'test-fail'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

And let's just say I'm trying to log the following test case to the logs/test-fail.log file specified in my logger:

logger = logging.getLogger('test')

def test_this(self):
   logger.debug('This message will print to the logs/test.log file')
   self.assertTrue(False) # will fail

In short, I want to print errors/failures from a Django TestCase using the logger and not using Bash. Also note that I'm fine with using the default logger, but I want to define an error logger case for only test cases, and I don't want the test error case being used by default.

1 Answers1

0

why not try changing the logger and handler level to ERROR ? (more info in case https://docs.djangoproject.com/en/2.2/topics/logging/#topic-logging-parts-loggers)

amr.kul
  • 37
  • 5
  • I can make the logger level ERROR, but how do I print out the message to the logger? Like if I want to print out a message, I can print `logger.error('Error message')`, but how to I capture that error message from a test failure/error? – KevinThePepper23 May 08 '19 at 21:15