Logging is an important part of every Django application. Developers use logs to understand application behavior, investigate errors, monitor user activity, and troubleshoot production issues. Login attempts, form submissions, payment operations, API requests, and validation failures are common events that applications record.
However, logging user-submitted values without proper handling can introduce a security vulnerability called log injection.
Log injection occurs when an attacker supplies specially crafted input that changes the structure or meaning of application log entries. For example, an attacker can submit a username containing newline characters and additional text that looks like a genuine log entry. If the application writes that value directly to an unstructured log file, the attacker may create fake entries or make real events harder to investigate.
Django uses Python's built-in logging framework, which provides flexible logging configuration. However, developers are responsible for handling untrusted values safely before including them in application logs.
This article explains how log injection works, why Django form values can create this risk, and how to protect application logs using input sanitization, structured logging, custom filters, and secure logging practices.
Understanding Log Injection
Log injection is a security issue that occurs when untrusted input is written to application logs without appropriate neutralization.
Most traditional application logs use one line for each event. For example:
2026-12-01 10:15:20 INFO Login failed for user john
2026-12-01 10:16:10 INFO Login successful for user alex
The problem starts when an application includes user-controlled data in a log message.
Imagine that a login form accepts a username containing a newline character followed by another message:
john
2026-12-01 10:15:20 INFO Login successful for user admin
If the application writes this value directly into an unstructured log, the output could look like this:
2026-12-01 10:15:20 WARNING Login failed for user john
2026-12-01 10:15:20 INFO Login successful for user admin
The second line may appear to be a genuine application event even though it came from the attacker's submitted username.
This can create confusion during security investigations because an administrator may incorrectly believe that an account successfully authenticated.
How CR and LF Characters Affect Logs
Two characters are particularly important when preventing log injection:
Together, these characters are commonly called CRLF.
Many traditional log formats use newline characters to separate individual records. If untrusted input contains these characters, it may introduce additional lines into the output.
Other control characters can also affect log viewers, terminal output, and downstream log-processing systems.
Why Django Form Values Are Untrusted
Django forms provide validation and cleaning mechanisms, but a valid form value is not automatically safe for every output context.
For example, a form may accept a username, comment, product name, or support message. Even if the value passes the form's validation rules, it may still contain characters that should not be written directly into an unstructured log.
Consider these examples:
Form field | Potential risk |
|---|
Username | Fake login or account activity entries |
Email address | Newline characters or misleading log content |
Contact message | Multiple injected log lines |
Product name | Unexpected control characters |
Search query | Extremely long or manipulated log entries |
File name | Misleading log output or terminal control characters |
The important principle is that form validation and safe logging are different responsibilities.
A Vulnerable Django Logging Example
Consider a Django login form that records failed authentication attempts.
The following example directly includes the submitted username in the log message:
import logging
from django.http import JsonResponse
from django.views.decorators.http import require_POST
logger = logging.getLogger(__name__)
@require_POST
def login_view(request):
username = request.POST.get("username", "")
# Authenticate the user here.
logger.warning(
f"Login failed for user: {username}"
)
return JsonResponse({
"message": "Invalid credentials"
}, status=401)
This code creates a problem because the username is controlled by the client.
An attacker can submit a value containing CR or LF characters. If the configured log formatter writes those characters as actual line breaks, the resulting log output may contain additional records.
The issue is not limited to login forms. The same problem can occur whenever an application logs values from:
Using an f-string or string concatenation is not the only problem. Even parameterized logging can remain vulnerable if the final log format does not safely encode untrusted values.
Sanitize Untrusted Values Before Logging
One straightforward defense is to normalize or remove dangerous control characters before writing user-submitted values to unstructured logs.
For example, create a reusable sanitization function:
import re
def sanitize_log_value(value, max_length=200):
if value is None:
return ""
value = str(value)
# Replace line breaks and other control characters.
value = re.sub(
r"[\x00-\x1f\x7f]",
" ",
value
)
# Limit the amount of user-controlled data.
return value[:max_length]
This function performs two important operations.
First, it replaces ASCII control characters, including CR and LF, with spaces. This prevents submitted values from introducing actual line breaks into a traditional single-line log record.
Second, it limits the length of the value. This reduces the possibility of an attacker submitting extremely large strings that create oversized log entries.
Use the function before logging the username:
import logging
from django.http import JsonResponse
from django.views.decorators.http import require_POST
logger = logging.getLogger(__name__)
@require_POST
def login_view(request):
username = request.POST.get("username", "")
safe_username = sanitize_log_value(
username,
max_length=100
)
logger.warning(
"Login failed for user: %s",
safe_username
)
return JsonResponse({
"message": "Invalid credentials"
}, status=401)
This approach makes the logged value safer for a conventional line-oriented log format.
However, sanitization should match the output destination. A terminal, HTML log viewer, plain-text file, and JSON log collector do not necessarily interpret characters in the same way.
For example, removing CR and LF is useful for line-oriented logs, but it does not replace HTML escaping when displaying log data in a browser.
Use Parameterized Logging
Python's logging framework supports parameterized logging. Instead of building the complete message before calling the logger, pass the message template and its values separately.
Consider this example:
logger.warning(
"Login failed for user: %s",
username
)
Python's logging framework performs message formatting when the record is emitted.
This approach has several benefits:
Keeps the message template separate from its values.
Avoids unnecessary string formatting when the message is filtered out.
Makes log messages easier to maintain.
Provides a consistent logging style.
However, parameterized logging alone does not prevent CRLF injection.
If the formatter writes the submitted username directly into a plain-text message, newline characters may still create additional log lines.
Therefore, combine parameterized logging with appropriate sanitization or structured logging.
Use Structured JSON Logging
Structured logging is one of the most useful approaches for preventing log injection.
Instead of building log messages as plain text, structured logging stores each event as a separate data record with named fields.
For example:
{
"level": "WARNING",
"event": "login_failed",
"username": "john",
"ip_address": "192.0.2.10"
}
If a username contains newline characters, a correctly implemented JSON encoder represents them as escaped characters inside the JSON string rather than as actual record-separating line breaks.
This preserves the structure of the log entry.
Python provides the json module, which can be used to create a simple JSON formatter.
Creating a JSON Log Formatter
Create a file named logging_formatters.py:
import json
import logging
from datetime import datetime, timezone
class JSONFormatter(logging.Formatter):
def format(self, record):
log_data = {
"timestamp": datetime.fromtimestamp(
record.created,
timezone.utc
).isoformat(),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage()
}
if hasattr(record, "event"):
log_data["event"] = record.event
if hasattr(record, "username"):
log_data["username"] = record.username
if record.exc_info:
log_data["exception"] = self.formatException(
record.exc_info
)
return json.dumps(
log_data,
ensure_ascii=True
)
The formatter converts each logging event into a JSON object.
The json.dumps() function escapes characters such as newline and quotation marks when they appear inside string values.
As a result, a submitted username containing CRLF characters remains part of the JSON value instead of creating another physical log record.
The formatter also includes the timestamp, severity level, logger name, and optional event information.
For production use, extend the formatter to include the fields required by your logging platform. Be careful not to serialize arbitrary objects or sensitive request data.
Configure JSON Logging in Django
Django supports logging configuration through the LOGGING setting in settings.py.
The following example configures a JSON formatter for a dedicated application logger:
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"json": {
"()": "myapp.logging_formatters.JSONFormatter",
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "json",
},
},
"loggers": {
"myapp": {
"handlers": ["console"],
"level": "INFO",
"propagate": False,
},
},
}
Replace myapp with the actual Python package name used by your Django application.
Now, application events written through the myapp logger use the JSON formatter.
Setting disable_existing_loggers to False helps preserve existing Django and third-party loggers. The dedicated configuration above does not automatically convert every log produced by Django or other libraries into JSON. Configure their handlers separately if a consistent JSON format is required across the entire application.
Logging Structured Events
You can now record events using additional fields:
import logging
logger = logging.getLogger(__name__)
def log_failed_login(username, ip_address):
logger.warning(
"Authentication failed",
extra={
"event": "login_failed",
"username": username,
"ip_address": ip_address
}
)
The formatter reads the additional fields and includes them in the JSON output.
A sample record could look like this:
{
"timestamp": "2026-12-01T10:15:20+00:00",
"level": "WARNING",
"logger": "myapp.views",
"message": "Authentication failed",
"event": "login_failed",
"username": "john",
"ip_address": "192.0.2.10"
}
The JSON encoder protects the structure of the record when the values contain special characters.
Structured logging also makes it easier to search for specific events, filter by username, and integrate with centralized logging platforms.
Create a Custom Logging Filter
Another approach is to use a custom logging filter.
Python logging filters can inspect or modify log records before they reach a handler.
For example, create a filter that sanitizes the message and its arguments:
import logging
import re
class SafeLogFilter(logging.Filter):
def filter(self, record):
if isinstance(record.msg, str):
record.msg = re.sub(
r"[\x00-\x1f\x7f]",
" ",
record.msg
)
record.args = self.sanitize_args(
record.args
)
return True
def sanitize_args(self, args):
if isinstance(args, dict):
return {
key: self.sanitize_value(value)
for key, value in args.items()
}
if isinstance(args, tuple):
return tuple(
self.sanitize_value(value)
for value in args
)
return self.sanitize_value(args)
def sanitize_value(self, value):
if isinstance(value, str):
value = re.sub(
r"[\x00-\x1f\x7f]",
" ",
value
)
return value[:200]
return value
Register the filter in Django's logging configuration:
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"filters": {
"safe_logs": {
"()": "myapp.logging_filters.SafeLogFilter",
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"filters": ["safe_logs"],
},
},
"loggers": {
"myapp": {
"handlers": ["console"],
"level": "INFO",
"propagate": False,
},
},
}
This filter provides a centralized place to normalize values for the configured handler.
However, this is a simplified implementation. A production filter should handle nested data structures, exception messages, custom objects, and non-string values according to the application's logging policy.
Also, a filter that modifies record.msg and record.args can affect other handlers when the same record is shared. If different handlers require different output formats, use handler-specific copies or formatters instead of globally modifying the record.
For most new applications, structured logging with a reliable JSON encoder is a cleaner foundation than attempting to sanitize every possible message format through one general-purpose filter.
Protect Sensitive Information in Logs
Preventing log injection is only one part of secure logging.
User-submitted form values may contain sensitive information that should never be stored in application logs.
For example, login forms may contain passwords, while payment forms may contain financial information.
Avoid logging complete request bodies or form dictionaries:
# Avoid this approach.
logger.info(
"Submitted form data: %s",
request.POST
)
This can expose passwords, authentication tokens, personal information, and other confidential values.
Instead, log only the information required for monitoring and troubleshooting:
logger.info(
"Login attempt received",
extra={
"event": "login_attempt",
"username": sanitize_log_value(
request.POST.get("username", ""),
max_length=100
)
}
)
For authentication events, consider using an internal user ID or a carefully designed identifier instead of storing the complete submitted username.
Never log passwords, session cookies, access tokens, refresh tokens, API keys, or other authentication secrets.
Handling Untrusted Values in Django Forms
A good logging strategy starts with clear separation between form validation and logging.
Django forms provide a convenient way to validate user-submitted values.
For example:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(
max_length=100
)
email = forms.EmailField()
message = forms.CharField(
max_length=2000
)
The view can validate the form and log a safe event without recording the complete message:
import logging
from django.http import JsonResponse
from django.views.decorators.http import require_POST
logger = logging.getLogger(__name__)
@require_POST
def contact_view(request):
form = ContactForm(request.POST)
if not form.is_valid():
logger.warning(
"Contact form validation failed",
extra={
"event": "contact_form_invalid"
}
)
return JsonResponse({
"message": "Invalid form data"
}, status=400)
name = form.cleaned_data["name"]
email = form.cleaned_data["email"]
logger.info(
"Contact form submitted",
extra={
"event": "contact_form_submitted",
"name": sanitize_log_value(name, 100)
}
)
return JsonResponse({
"message": "Contact form submitted successfully"
})
This example validates the submitted data and records a limited amount of information.
The email address and message are not logged because the application does not need them to confirm that the form was submitted.
In a real application, the validated information can be saved to a database or processed by a background task according to the application's requirements.
Common Mistakes When Preventing Log Injection
Assuming Form Validation Prevents Log Injection
Django form validation checks whether submitted values meet the rules defined by the application.
It does not automatically make those values safe for every output destination.
A valid string can still contain newline characters or other control characters. Apply logging-specific protections before including untrusted data in logs.
Assuming Parameterized Logging Is Enough
Parameterized logging improves message construction, but it does not automatically neutralize dangerous characters.
A plain-text formatter may still write embedded newline characters as actual line breaks.
Use structured logging or an appropriate sanitization strategy.
Replacing Only Newline Characters
Removing only \n may leave carriage return characters, tabs, and other control characters.
For conventional single-line logs, define a consistent policy for the control characters that your application accepts.
Logging the Complete Request
Logging request.POST, request.body, or complete form data can expose sensitive information and introduce additional untrusted content.
Record only the fields required for a specific operational or security purpose.
Applying Sanitization Only in the View
If every view implements its own sanitization logic, developers may eventually forget to apply it in a new endpoint.
Use shared logging utilities, structured formatters, or handler-specific filters to make secure logging consistent across the application.
Trusting JSON Without Checking the Formatter
Structured logging helps prevent record-boundary manipulation only when values are encoded correctly.
Manually building JSON strings with concatenation or inserting raw user values into a JSON template can recreate the same problem.
Use a proper JSON serializer such as Python's json.dumps() or a maintained structured logging library.
Ignoring Log Viewer Security
Even correctly structured logs can become dangerous when a dashboard displays untrusted values as HTML without escaping them.
Ensure that the log viewing interface safely renders user-controlled content. JSON encoding does not replace output encoding in a browser.
Testing Log Injection Protection
Security testing should include values that contain newline characters, control characters, long strings, and special symbols.
For example:
malicious_username = (
"john\r\n"
"2026-12-01 INFO Login successful for admin"
)
safe_username = sanitize_log_value(
malicious_username
)
assert "\r" not in safe_username
assert "\n" not in safe_username
You can also test the JSON formatter:
import json
import logging
record = logging.LogRecord(
name="myapp",
level=logging.WARNING,
pathname=__file__,
lineno=10,
msg="Login failed for user: %s",
args=("john\r\nfake log entry",),
exc_info=None
)
formatted = JSONFormatter().format(record)
parsed = json.loads(formatted)
assert parsed["message"] == (
"Login failed for user: john\r\nfake log entry"
)
The parsed JSON value contains the original newline characters, but the serialized JSON output represents them as escaped characters. They do not create additional physical log records.
For a complete test, write several records to a temporary log file and verify that each event occupies one physical line. Also test how the records appear in the actual log collector and dashboard used by the application.
Django's test framework can be used to submit malicious values through form endpoints and verify that the resulting logs remain correctly structured.
Best Practices for Secure Django Logging
Treat all user-controlled values as untrusted, including values from forms, headers, query parameters, and uploaded files.
Use structured JSON logging for application events.
Use a proper JSON encoder rather than manually constructing JSON strings.
Sanitize CR, LF, and other relevant control characters before writing values to unstructured logs.
Apply a reasonable length limit to user-controlled log fields.
Use parameterized logging to keep message templates separate from values.
Avoid logging passwords, tokens, session identifiers, and sensitive personal information.
Log meaningful event names instead of complete request payloads.
Centralize logging configuration and reusable sanitization logic.
Ensure every relevant logging handler uses an appropriate formatter or filter.
Protect log files and centralized log storage with access controls.
Escape untrusted values when displaying logs in HTML interfaces.
Test malicious input against the complete logging pipeline, including collectors and dashboards.
Review log retention and access policies regularly.
Advantages and Disadvantages of Secure Logging Approaches
Approach | Advantages | Disadvantages |
|---|
Input sanitization | Simple to implement and useful for existing applications | Must match the output format and be applied consistently |
Parameterized logging | Improves message construction and avoids unnecessary formatting | Does not independently prevent CRLF injection |
Structured JSON logging | Preserves record boundaries and supports log analysis | Requires compatible formatters and log collectors |
Custom logging filters | Centralizes processing for configured handlers | Can become complex and may affect shared log records |
Minimal logging | Reduces sensitive data exposure and unnecessary log content | May provide less detail during troubleshooting |
No single approach replaces a complete logging security policy. A combination of structured logging, careful data selection, input handling, and secure log storage provides stronger protection.
Conclusion
Log injection can make Django application logs unreliable by allowing attackers to manipulate log entries through untrusted form values. Newline characters, control characters, and oversized input can affect traditional logging formats and make security investigations more difficult.
Preventing this vulnerability requires more than basic form validation. Developers should treat every user-controlled value as untrusted when writing logs, use structured JSON logging, sanitize values when working with plain-text formats, and avoid recording sensitive request information.
Django's logging system provides the configuration flexibility needed to implement these protections using Python logging formatters, filters, and handlers.
For production applications, the most practical approach is to use structured logging with proper JSON encoding, keep log messages focused on meaningful events, and test the complete logging pipeline with malicious input. This helps maintain accurate, searchable, and trustworthy logs without exposing sensitive user information.
Join the conversation! Your thoughts help the community grow.