Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log Python warnings in a Django log file?

Tags:

python

django

I have a Django application that I am migrating from v1.8 to v1.10. In the process of doing this work, I ran my application via:

python -Wall manage.py runserver

Doing so causes a number of Python warnings to appear in my console. I'd like to have these warnings show up in my Django application log, so I can examine them later. I thought my application's log handler would catch these warnings, but it doesn't. The log handler looks like the following (as taken from settings.py):

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt': "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file': {
            'level': 'WARNING',
            'class': 'logging.FileHandler',
            'filename': 'myapp.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'propagate': True,
            'level': 'WARNING',
        },
        'myapp': {
            'handlers': ['file'],
            'level': 'WARNING',
        },
    }
}

How can I capture Python warnings (with -Wall) in my Django log for examination later?

like image 976
Jonah Bishop Avatar asked Nov 22 '16 22:11

Jonah Bishop


People also ask

How do you log a warning in Python?

Python provides a built-in integration between the logging module and the warnings module to let you do this; just call logging. captureWarnings(True) at the start of your script and all warnings emitted by the warnings module will automatically be logged at level WARNING .

How do I log activity in Django?

You can implement a user activity monitoring system by adding the GitHub Gist at the bottom to any admin.py file in your project. This will allow you to see any change, addition, and deletion that happens in any model and know who made it by using the already saved data of Django Admin's LogEntry model.

Where are Django logs stored?

The Django One-Click application employs Gunicorn and Upstart. Application level logging can be found in /var/log/upstart/gunicorn. log By default, Gunicorn logs to stderr and Upstart will collect output to stderr/stdout in /var/log/upstart/$JOB_NAME.

What is logging in Django and how to configure logging?

Basically, logging provides the different techniques to configure the logging and ranging that means interface to configuration files. In python, we have a logging library but Django uses by default configuration format that is nothing but the dictConfig.

What is the default logging severity level in Django?

If you’re using Django’s default logging configuration, the message will appear in the console. The WARNING level used in the example above is one of several logging severity levels: DEBUG , INFO, WARNING, ERROR, CRITICAL. So, another example might be: Records with a level lower than WARNING will not appear in the console by default.

How to log messages to a file in Python?

Python – Logging Messages to Log File. Using Python Logging module, you can log debug lines, information, warnings, errors and critical errors to a log file instead of echoing to the console. To log data to a file, using the logging basic configuration, set the filename with the location to the log file. If the file is not present, the Python ...

What is the difference between logger and handler in Django?

Django's logging module consist four players. Logger is the entry point to any logging system. It is kind of a bucket with a name where you push your error message. Handler decides what needs to be done for each message in logger.


1 Answers

The warnings shown in python -Wall manage.py <command> are generated using warnings module. In Python2.7 logging module documentation, they have a section showing how to integrate messages from warnings module to logging.

Add these to your settings file.

import logging
logging.captureWarnings(True)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt': "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file': {
            'level': 'WARNING',
            'class': 'logging.FileHandler',
            'filename': 'myapp.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'propagate': True,
            'level': 'WARNING',
        },
        'myapp': {
            'handlers': ['file'],
            'level': 'WARNING',
        },
        'py.warnings': {
            'handlers': ['file'],
            'level': 'WARNING',
            'propagate': True
        }
    }
}

After adding it, try to run any manage.py command and you can see the warnings written to your myapp.log file.

This line instructs logging to capture the py.warnings warnings:

    logging.captureWarnings(True)

This instructs logging to route (in this example to the file handler) warnings from the py.warnings logger:

    'py.warnings': {
        'handlers': ['file'],
        'level': 'WARNING',
        'propagate': True
    }
like image 100
Jayakrishnan Damodaran Avatar answered Nov 03 '22 02:11

Jayakrishnan Damodaran