Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop logging in Django unittests from printing to stderr?

I'm testing some Django models with bog-standerd django.test.Testcase. My models.py writes to a debug log, using the following init code:

import logging
logger = logging.getLogger(__name__) # name is myapp.models

and then I write to the log with:

logger.debug("Here is my message")

In my settings.py, I've set up a single FileHandler, and a logger for myapp, using that handler and only that handler. This is great. I see messages to that log. When I'm in the Django shell, I only see messages to that log.

When, however, I run my test suite, my test suite console also sees all those messages. It's using a different formatter that I haven't explicitly defined, and it's writing to stderr. I don't have a log handler defined that writes to stderr.

I don't really want those messages spamming my console. I'll tail my log file if I want to see those messages. Is there a way to make it stop? (Yes, I could redirect stderr, but useful output goes to stderr as well.)

Edit: I've set up two handlers in my settings.py:

'handlers': {
    'null': {
        'level': 'DEBUG',
        'class': 'django.utils.log.NullHandler',
    },
    'logfile' : {
        'level':'DEBUG',
        'class':'logging.FileHandler',
        'filename':'%s/log/development.log' % PROJECT_DIR,
        'formatter': 'simple'
    },
},

and tried this:

'loggers': {
    'django': {
        'level': 'DEBUG',
        'handlers': ['null']
    },
    'myapp': {
        'handlers': ['logfile'],
        'level':'DEBUG',
    },

... but the logging / stderr dumping behavior remains the same. It's like I'm getting another log handler when I'm running tests.

like image 402
Nate Avatar asked Jan 09 '12 20:01

Nate


1 Answers

It's not clear from your config snippet which handlers, if any, are configured for the root logger. (I'm also assuming you're using Django 1.3.) Can you investigate and tell us what handlers have been added to the root logger when you're running tests? AFAICT Django doesn't add anything - perhaps some code you're importing does a call to basicConfig without you realising it. Use something like ack-grep to look for any occurrences of fileConfig, dictConfig, basicConfig, and addHandler - all of which could be adding a handler to the root logger.

Another thing to try: set the propagate flag to False for all top-level loggers (like "django", but also those used by your modules - say "myapp"). Does that change things?

like image 76
Vinay Sajip Avatar answered Oct 26 '22 00:10

Vinay Sajip