You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中print语句无法写入日志文件的解决方法咨询

How to Capture print() Output in Django's Log File

Got it, let's get your print statements showing up in that log file! The core issue here is that print() sends output directly to stdout/stderr, which isn't connected to Django's logging pipeline by default. Here are two reliable ways to fix this:

Option 1: Redirect stdout/stderr to Logging

This method captures all output that would normally go to the console (including print statements) and routes it to your logging system.

First, update your LOGGING config in settings.py to include a root logger (this ensures all captured output gets directed to your file handler):

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,  # Critical: don't disable default loggers
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'logs.log',
            'formatter': 'simple'
        },
    },
    'root': {  # Root logger catches all log messages
        'handlers': ['file'],
        'level': 'INFO',
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

Next, add this code to your project's entry point (like wsgi.py or asgi.py) to redirect stdout/stderr:

import sys
import logging

class PrintLogger:
    def write(self, message):
        # Skip empty lines (print adds a newline automatically)
        if message.strip():
            logging.info(message.strip())

# Override stdout and stderr to use our logger
sys.stdout = PrintLogger()
sys.stderr = PrintLogger()

Option 2: Replace the print() Function Directly

If you'd prefer to target only print() calls specifically, you can override the global print function to use logging instead. Add this code to your project's initialization file (like settings.py or a custom startup script):

import logging

def print(*args, **kwargs):
    # Replicate the default print behavior by joining arguments into a string
    message = ' '.join(map(str, args))
    # Log the message at INFO level (adjust level if needed)
    logging.info(message)

Key Notes

  • Restart Your Server: Changes to logging config or startup code won't take effect until you restart Django's runserver or your production server (e.g., Gunicorn/UWSGI).
  • File Permissions: Make sure the user running Django has write access to the logs.log file's directory.
  • Log Level Adjustments: If you want print statements logged at a different level (like DEBUG), just change logging.info() to logging.debug() in the code above, and ensure your file handler's level is set to DEBUG (which it already is in your config).

内容的提问来源于stack exchange,提问作者soubhagya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:02:52