Reputation: 2541
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.
Upvotes: 11
Views: 31116
Reputation: 444
Just add print(players)
in loop and it will print results in terminal.
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:
print(players)
data[user.email] = players
logger.info(data)
Upvotes: 1
Reputation: 22031
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 !
Upvotes: 3
Reputation: 20349
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
Upvotes: 7
Reputation: 359
Assuming your project is running on linux, it depends if runserver is on nohup. If not then all print statements will be visible on command line otherwise if its running on nohup then run the below command on command line.
tail -f nohup.out
Upvotes: 0
Reputation: 3104
As @Andriy say you can use logging. It's get working out of the box.
If you want to pretty print dictionary you can use pprint
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(yourdict)
Upvotes: 0