Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django how to print data when using runserver

Tags:

django

I have a dictionary data with how many players every user created:

views.py

def statistics(request):
    users = User.objects.all()
    data = dict()
    for user in users:
        players = Players.objects.filter(created__email=user.email).count()
        if players > 0:
            data[user.email] = players
            logger.info(data)

How can i print this dictionary in the console when i use runserver? I have seen django loggers but i didn't understand them fully.

like image 525
alex Avatar asked Oct 25 '17 11:10

alex


People also ask

What does Runserver do in Django?

The runserver command is a built-in subcommand of Django's manage.py file that will start up a development server for this specific Django project.

Where does Django print to?

If you are using apache2 server to run django application and enabled access & error logs, your print statements will be printed in the error logs. mostly apache2 logs will be in this location /var/log/apache2/ .

How do I keep Django server running?

Start your server there. Then press Ctrl-a, then d. This detach the screen session, keeping it running in the background.


2 Answers

You should do like

import os

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'filters': ['require_debug_true'],
        },
    },
    'loggers': {
        'mylogger': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
            'propagate': True,
        },
    },
}

This will be printing to console when DEBUG = True (normally use runserver). Then you can do

import logging
logger = logging.getLogger("mylogger")
logger.info("Whatever to log")

Refer doc

like image 194
itzMEonTV Avatar answered Nov 14 '22 05:11

itzMEonTV


Setup logging in your django settings file:

import os

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
        },
    },
}

Then you can start logging in your view:

import logging
logger = logging.getLogger(__name__)

# Put the logging info within your django view
logger.info("Simple info")

See more information on the Logging | Django Documentation

Good Luck !

like image 40
Andriy Ivaneyko Avatar answered Nov 14 '22 04:11

Andriy Ivaneyko