I am trying to learn logging module in Django. I want to write exceptions to the log file so that I can see them later. Printing log messages on console is working fine but I am unable to write the same log messages to the log file. Below is my code.
My settings.py
LOGGING = {
'version': 1,
'loggers': {
'django':{
'handlers': ['file'] ,
'level':'INFO'
}
},
'handlers':{
'file':{
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'debug.log',
}
}
}
My views.py
def Helloworld(request):
try:
s = HttpResponse("this is life")
logging.debug("this is debug log - in hw page")
logging.critical("this is critical log - in hw page")
logging.error("this is error log - in hw page")
except Exception as e:
print(e)
logging.critical("this is critical log - in hw page - exception")
logging.exception(e)
return s
My console output
Django version 3.0.6, using settings 'project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
CRITICAL:root:this is critical log - in hw page
ERROR:root:this is error log - in hw page
INFO:django.server:"GET /hw HTTP/1.1" 200 12
My output of log file
Watching for file changes with StatReloader
"GET /hw HTTP/1.1" 200 12
C:\Users\....\views.py changed, reloading.
Watching for file changes with StatReloader
Watching for file changes with StatReloader
"GET /hw HTTP/1.1" 200 12
"GET /hw HTTP/1.1" 200 12
C:\Users\...\views.py changed, reloading.
Watching for file changes with StatReloader
C:\Users\...\views.py changed, reloading.
Watching for file changes with StatReloader
"GET /hw HTTP/1.1" 200 12
My Urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include(router.urls)),
url(r'^hw$', Helloworld),
url('__debug__/', include(debug_toolbar.urls)),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Please let me know where I am going wrong. I want the same text which is printed in the console to be written in the log file.
My logging configuration in settings.py was incorrect. The correct configuration is below.
LOGGING = {
'version': 1,
'formatters': {
'standard': {
'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
},
},
'loggers': {
'':{
'handlers': ['file'] ,
'level':'DEBUG'
}
},
'handlers':{
'file':{
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'debug.log',
'formatter': 'standard'
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.