How to create different custom logs formatter for Info, Warning and Error logs in Django web application?
Published on May 18,2020 by Maulik
If you are interested in something which helps you customize the logs format for Django web applications running in production, you have landed at the perfect place. Django web framework provides the flexibility to customize the format of your log. I would love to have complete information in logs rather than having not required out there and missing vital information like which file and which line number wrote this log. I want to have a log level, file name, line number, and message in the log information.
What is custom log formatter in Django web applications?
For example,
Below is the Info logs format which we want to have with our Django web application
<Log Level>: <Message> - <File Location>:<Line No>
Below is the Warning logs format which we want to have with our Django web application
<Log Level>: <Message>
Below is the Error logs format which we want to have with our Django web application
<Log Level>: <Datetime> <Filename> <Http Method> <Message> <File Location> <Line No.>
Let us create one custom logs formatter which can have log level, insert line number, and file name as mentioned above.
What is the need for a custom log formatter for different log levels for the Django web application?
- In the working world, as the product expands in production with an increase in user base, scalability, and maintenance of the application start becoming a challenge.
- To equip the support team with the right information required to file a bug ticket for the Django application.
- With an increase in the volume of load on the Django web application server, you would like to avoid storing unnecessary information parameters from a specific log level. And would like to get more attributes of information for critical log levels.
- Custom log formats prove an excellent approach when your Django web application is live and has many users.
- But it is always a good practice to have this type of standard implemented for all Django web application development projects.
Steps to implement custom log formatter for different log levels in Django web application
- Create a custom Log Filter Class.
- Update custom logging settings in settings.py
- Add sample logs from views file.
- View different log formats for Info, Warning, and Error logs.
Please check custom log formatter for different log levels Django application repository on Github
Create a custom Log Filter Class.
Please check :
├── logging_formatter/log_middleware.py
import logging
class FilterLevels(logging.Filter):
def __init__(self, filter_levels=None):
super(FilterLevels, self).__init__()
self._filter_levels = filter_levels
def filter(self, record):
if record.levelname in self._filter_levels:
return True
return False
- We have created a custom filter by extending “logging.Filter” class. It helps choose different log formats for different log levels of the Django web application.
Update custom logging settings in settings.py
- Let us update logging configuration in settings.py as follows:
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'filters': {
'filter_info_level': {
'()': 'logging_formatter.log_middleware.FilterLevels',
'filter_levels' : [
"INFO"
]
},
'filter_error_level': {
'()': 'logging_formatter.log_middleware.FilterLevels',
'filter_levels' : [
"ERROR"
]
},
'filter_warning_level': {
'()': 'logging_formatter.log_middleware.FilterLevels',
'filter_levels' : [
"WARNING"
]
}
},
'formatters': {
'info-formatter': {
'format': '%(levelname)s : %(message)s - [in %(pathname)s:%(lineno)d]'
},
'error-formatter': {
'format': '%(levelname)s : %(asctime)s {%(module)s}
[%(funcName)s] %(message)s- [in %(pathname)s:%(lineno)d]',
'datefmt': '%Y-%m-%d %H:%M'
},
'short': {
'format': '%(levelname)s : %(message)s'
}
},
'handlers': {
'customHandler_1': {
'formatter': 'info-formatter',
'class': 'logging.StreamHandler',
'filters': ['filter_info_level'],
},
'customHandler_2': {
'formatter': 'error-formatter',
'class': 'logging.StreamHandler',
'filters': ['filter_error_level'],
},
'customHandler_3': {
'formatter': 'short',
'class': 'logging.StreamHandler',
'filters': ['filter_warning_level'],
},
},
'loggers': {
'customLogger': {
'handlers': [
'customHandler_1',
'customHandler_2',
'customHandler_3'
],
'level': 'DEBUG',
},
},
}
Add sample logs from views file.
Please check :
├── logging_formatter/views.py
from rest_framework.response import Response
from rest_framework.views import APIView
import logging
logger = logging.getLogger('customLogger')
class UserView(APIView):
def get(self, request):
logger.info("Init log from view")
logger.warning("Init warning from view")
logger.error("Test error")
return Response("Success")
View different log formats for Info, Warning, and Error logs in the Django application.
We can notice the following outcome on the console:
INFO : Init log from view - [in /home/swan-13/Documents/project/blog-projects/repo/logging-formatter-repo/demo/logging_formatter/logging_formatter/views.py:9]
WARNING : Init warning from view
ERROR : 2020-04-11 13:57 {views} [get] Test error- [in /home/swan-13/Documents/project/blog-projects/repo/logging-formatter-repo/demo/logging_formatter/logging_formatter/views.py:11]
Conclusion:
We have created three different formats for three different log levels. I highly recommend this implementation in all Django web application development projects.
Thank you for taking the time to read this article. I am sure it solves your multiple problems while providing support for the product built on the Django framework.
If you are looking for a tool to search, read and manage logs please check Integrate Google Stackdriver logging with Django web application
46 Comments
DouglasMaH
5 hours, 13 minutes
clomid tablets for sale <a href=" https://clomidclo.com/# ">clomid tablets for sale</a> where to buy cheap clomid online
DouglasMaH
1 day, 12 hours
ivermectin without a doctor prescription <a href=" https://stromectolive.com/# ">stromectol pills for humans</a> stromectol 12 mg tablets
DouglasMaH
2 days, 4 hours
sildenafil 100 mg lowest price <a href=" https://viagrasln.com/# ">price for viagra</a> sildenafil citrate 100mg for sale
Stromclall
3 days, 3 hours
canadian pharmaceuticals online safe <a href=" https://canadadrs.com/# ">reputable canadian mail order pharmacies</a> buying from canadian online pharmacies
Stromclall
3 days, 19 hours
herbal ed treatment <a href=" https://edpilldrs.com/# ">gnc ed pills</a> ed medication online
GregoryBUP
6 days, 13 hours
ivermectin side effects in humans <a href=" https://stromectolca.com/# ">stromectol buy</a> ivermectin and heart disease
GregoryBUP
1 week
buy prescription drugs from canada <a href=" https://canadapillsshop.com/# ">legal to buy prescription drugs without prescription</a> canadian drug pharmacy
GregoryBUP
1 week
finasteride without prescription <a href=" https://finasteridemen.com/# ">purchase propecia</a> finasteride cost
Liatunk
1 week, 1 day
Ykbwaa Gd Sildnafil [url=https://newfasttadalafil.com/]Cialis[/url] Acheter Dapoxetine Paypal Lwzcdh Xmijgv <a href=https://newfasttadalafil.com/>Cialis</a> Bxjuun Grkqtt https://newfasttadalafil.com/ - Cialis
GregoryBUP
1 week, 1 day
prosteride <a href=" https://finasteridemen.com/# ">propecia cheapest no prescription</a> finasteride tablets
GregoryBUP
1 week, 2 days
where to get propecia <a href=" https://finasteridemen.com/# ">propecia india</a> generic propecia cheap
GregoryBUP
1 week, 3 days
cost of propecia <a href=" https://finasteridemen.com/# ">finasteride hair loss</a> generic propecia without prescription
JamesoMigh
1 week, 5 days
ivermectin dosage for cats mange <a href=" https://stromectolmrt.com/# ">ivermectin eye drops</a> ivermectin for demodex mites in dogs
JamesoMigh
1 week, 6 days
is ed reversible <a href=" https://cheapdrugsmrt.com/# ">erectile dysfunction drug</a> best ed treatment
JamesoMigh
1 week, 6 days
prednisone 10 <a href=" https://prednisonemrt.online/# ">prednisone 10mg tablet cost</a> prednisone 20mg tab price
JamesoMigh
2 weeks
prednisone 1 mg for sale <a href=" https://prednisonemrt.com/# ">prednisone 15 mg daily</a> 50mg prednisone tablet
JamesoMigh
2 weeks
tractor supply ivermectin <a href=" https://stromectolmrt.com/# ">order stromectol over the counter</a> ivermectin stromectol
JamesoMigh
2 weeks, 1 day
nih approved ivermectin <a href=" https://stromectolmrt.com/# ">ivermectin 6 tablet</a> what is ivermectin derived from
JamesoMigh
2 weeks, 2 days
drugs prices <a href=" https://cheapdrugsmrt.com/# ">drugs to treat ed</a> how to cure ed
Charleswar
2 weeks, 4 days
<a href=" https://stromectol.company/# ">ivermectin dosage cats</a> ivermectin for humans lice
Stacyliz
2 weeks, 5 days
male erection <a href=" http://cheapdrugs.icu/# ">home remedies for ed</a> best natural ed treatment
Stacyliz
2 weeks, 6 days
no prescription prednisone canadian pharmacy <a href=" https://deltasone.shop/# ">can you buy prednisone over the counter in usa</a> prednisone 20mg online without prescription
Stacyliz
3 weeks, 1 day
erectile dysfunction treatments <a href=" http://cheapdrugs.store/# ">vacuum pumps for ed</a> medications for
Stacyliz
3 weeks, 2 days
can i buy prednisone over the counter in usa <a href=" https://deltasone.shop/# ">online prednisone 5mg</a> prednisone canada pharmacy
bnpmclydt
3 weeks, 2 days
Django Circle | How to create different custom logs formatter for Info, Warning and Error logs in Django web application? <a href="http://www.g98p1xr38t39i24l1q45tndupd7wu044s.org/">abnpmclydt</a> [url=http://www.g98p1xr38t39i24l1q45tndupd7wu044s.org/]ubnpmclydt[/url] bnpmclydt http://www.g98p1xr38t39i24l1q45tndupd7wu044s.org/
HaroldArbib
3 weeks, 4 days
generic ed pills <a href=" http://drugsfast.store/# ">erectile dysfunction remedies</a> ed clinics
HaroldArbib
3 weeks, 6 days
best drugs for ed <a href=" http://drugsfast.store/# ">online drug store</a> viagra without doctor prescription
HaroldArbib
4 weeks
ed medicine online <a href=" http://drugsen.site/# ">the best ed drug</a> real viagra without a doctor prescription
HaroldArbib
4 weeks, 1 day
natural herbs for ed <a href=" https://drugsus.shop/# ">medication online</a> erection pills online
FrankNurse
1 month
how can i get doxycycline over the counter <a href=" https://doxycyclinemst.com/# ">doxcyclene</a> doxycycline online uk
FrankNurse
1 month
doxycycline 100mg capsules buy <a href=" https://doxycyclinemst.com/# ">doxycycline capsules purchase</a> doxycycline medicine
FrankNurse
1 month
doxycycline 100mg tablet price in india <a href=" https://doxycyclinemst.com/# ">doxycycline prescription discount</a> doxycycline hyclate 100 mg capsules
FrankNurse
1 month
over the counter amoxicillin canada <a href=" http://amoxilen.store/# ">amoxicillin 500 mg online</a> over the counter amoxicillin canada
FrankNurse
1 month
doxycycline hyclate 100 mg <a href=" http://doxycyclineus.site/# ">buy doxycycline online 270 tabs</a> doxycycline 500mg
FrankNurse
1 month, 1 week
buy prednisone canada <a href=" https://prednisoneus.shop/# ">prednisone medicine</a> prednisone 5 tablets
FrankNurse
1 month, 1 week
buy clomid online uk 50mg <a href=" http://clomidfast.site/# ">clomid 2017</a> how much is clomid uk
EdwardAbimb
1 month, 1 week
cialis viagra australia <a href=" http://cialiscnd.com/# ">what is the cost of cialis</a> cialis purchase in kuwait
EdwardAbimb
1 month, 1 week
cialis hk <a href=" http://cialiscnd.com/# ">cialis on line new zealand</a> cialis buy online
Strojoism
1 month, 2 weeks
stromectol 3mg tablets <a href=" https://stromectolns.com/# ">ivermectin topical for humans</a> ivermectin pharmacology
Artrcriff
1 month, 2 weeks
cialis and viagra together <a href=" https://cls20.com/# ">google south africa cialis</a> original cialis online
Travismindy
1 month, 2 weeks
viagra online without prescription <a href=" https://edviagralove.com/# ">do i need a prescription for viagra</a> what happens when a girl takes viagra
AbrtNew
2 months, 1 week
<a href="https://t.me/filmfilmfilmes/13">12 лет рабства</a>
AbrtNew
2 months, 1 week
http://bit.ly/legenda-destan-vse-serii
AbrtNew
2 months, 1 week
http://bit.ly/legenda-destan-vse-serii
AbertNew
2 months, 2 weeks
скільки триватиме війна в україні <a href="http://bitly.com/skilky-shche-bude-tryvaty-viyna-v-ukrayini">коли закінчиться війна в україні 2022 передбачення</a> коли закінчиться війна в україні 2022
POF998QS www.yandex.ru
5 months
POF998QS www.yandex.ru