Wednesday, 2 November 2022

python django logging

 Easiest logging :

# sys.stderr is output to console

using print with file=sys.stderr


https://stackoverflow.com/questions/4558879/python-django-log-to-console-under-runserver-log-to-file-under-apache

import sys

print("Goodbye cruel world!", file=sys.stderr)



Using django logging :

https://www.sentinelone.com/blog/getting-started-quickly-django-logging/#:~:text=The%20simplest%20possible%20logging%20we,creates%20it)%20logger%20%3D%20logging.


configure logging in settings.py

:LOGGING = {

    'version': 1,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/path/to/your/file.log',
            'formatter': 'simple'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

then in ur file

import logging

from django.http import HttpResponse

# This retrieves a Python logging instance (or creates it)
logger = logging.getLogger(__name__)

def index(request):
    # Send the Test!! log message to standard out
    logger.error("Test!!")
    return HttpResponse("Hello logging world.")

#Running that as before and refreshing the browser, the console log message now includes the additional information from our format string:

$ python manage.py runserver
...
November 29, 2018 - 14:36:56
Django version 2.1.3, using settings 'app.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
hello.views  ERROR    Test!!

No comments:

Post a Comment