Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging django.request to file instead of console

I am trying to configure my django settings.py to properly use the python logging facility but I've stumbled upon a rather strange problem:

Even after reading the docs, I simply can't find out how to redirect the console printed debug request lines from Django to a file I've specified; Below is part of my logging configuration.

LOGGING = {
    'version': 1,
    'formatters': {
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    }
    'handlers': {
        'file_http': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': r'C:\mysystem-http.log',
            'formatter': 'verbose'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['file_http'],
            'level': 'DEBUG',
            'propagate': False
        }
    }
}

I keep seeing my console print line of the following format:

[19/Dec/2014 11:48:03] "POST /api/v1/ HTTP/1.1" 200 10

How may I redirect these to a file using the logging facility?

Thanks in advance

like image 363
stratis Avatar asked Dec 19 '14 10:12

stratis


2 Answers

manage.py runserver is not using logging system for messages like [19/Dec/2014 11:48:03] "POST /api/v1/ HTTP/1.1" 200 10. Instead of this, runserver uses sys.stderr (and sys.stdout for others messages). If you really need to redirect this to file you can override sys.stderr settings.py. Example - logging sys.stderr to file and console:

import sys

class Logger(object):
    def __init__(self):
        self.console = sys.stderr
        self.file = open("runserver.log", "a", 0)

    def write(self, msg):
        self.console.write(msg)
        self.file.write(msg)

sys.stderr = Logger()

In write method you can use logging system to handle this by LOGGING settings as well.

Update:

In Django 1.10, runserver output goes through logging: https://docs.djangoproject.com/en/dev/releases/1.10/#runserver-output-goes-through-logging

like image 88
dikamilo Avatar answered Sep 28 '22 12:09

dikamilo


These outputs are handled by your HTTP server (WSGIServer from the standard library if running in dev mode).

The configuration of your settings.py has nothing to do with it.

like image 21
Benjamin Toueg Avatar answered Sep 28 '22 14:09

Benjamin Toueg