Welcome back to CodeYourCraft! Today, we're diving into Django's powerful logging system - Log Handlers. Let's get started! π―
In Django, Log Handlers are responsible for capturing and managing application logs. They can be used to write log messages to various destinations such as files, syslog, or even the console.
Let's create a custom log handler that writes log messages to a file.
import logging
from logging.handlers import RotatingFileHandler
class RotatingFileAppender(RotatingFileHandler):
def __init__(self, filename, maxBytes=1048576, backupCount=9, encoding=None, delay=0):
super().__init__(filename, maxBytes=maxBytes, backupCount=backupCount, encoding=encoding, delay=delay)
self.filename = filename
def emit(self, record):
super().emit(record)
self.doRotate() # Rotate the log file immediately after writing a recordThis custom handler rotates the log file immediately after writing a record, which is useful for keeping the log file size manageable.
Now, let's configure our custom handler in settings.py:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'custom_file_handler': {
'class': 'yourapp.utils.RotatingFileAppender',
'filename': 'myapp.log',
'maxBytes': 1048576, # 1 MB
'backupCount': 9,
},
},
'loggers': {
'yourapp': {
'handlers': ['custom_file_handler'],
'level': logging.DEBUG,
},
},
}Replace yourapp with the name of your Django app. Now, whenever you log a message at the DEBUG level or higher, it will be written to myapp.log.
import logging
from django.utils.log import get_logger
logger = get_logger(__name__)
def some_function():
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")In this example, we're logging messages of various levels. Let's see what our custom log handler does with them!
Which log level writes the most verbose log messages?
Keep learning, and we'll see you in the next tutorial! π