Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django "./manage.py runserver" log to file instead of console

Tags:

python

django

Running python manage.py runserver will initiate Django's development server and all logs are printed to the console.

I need to write the logs in a django.log file instead of console.

Django logging documentation is good, but I cant seem to configure the logging to log the same as python manage.py runserver.

Question: How can I log everything from ./manage.py runserver to a file?

like image 549
Vingtoft Avatar asked Nov 21 '16 10:11

Vingtoft


2 Answers

It is a simple linux redirect, so it should look something like this:

python manage.py runserver 0.0.0.0:8080 >> log.log 2>&1

Please note that I've set 8080 as the local port, you should change it according your project.

PS: This method (manage runserver) should be used for development only, not for deployment.

like image 123
Adriano Martins Avatar answered Nov 01 '22 19:11

Adriano Martins


These are some sample settings that should make sure that logs are written to both console and file. You can add/modify this in your dev-settings:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
        },
    },
    'handlers': {
        # this is what you see in runserver console
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'standard',
        },
        # this handler logs to file
        #▼▼▼▼ this is just a name so loggers can reference it
        'file': {  
            'class': 'logging.FileHandler',
            #  choose file location of your liking
            'filename': os.path.normpath(os.path.join(BASE_DIR, '../../logs/django.log')),  
            'formatter': 'standard'
        },
    },
    'loggers': {
        # django logger
        'django': {
            # log to console and file handlers
            'handlers': ['console', 'file'],  
            'level': os.getenv('DJANGO_LOG_LEVEL', 'ERROR'),  # choose verbosity
        },
    },
}
like image 43
user2390182 Avatar answered Nov 01 '22 19:11

user2390182