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.
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.
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/ .
Start your server there. Then press Ctrl-a, then d. This detach the screen session, keeping it running in the background.
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
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 !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With