Django8 LOG

App.tests

import logging

logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("log.txt")
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
# 創建log.txt文件
run tests

settings

DEBUG = False

# smtp服務的郵箱服務器
EMAIL_HOST = 'smtp.163.com'
# smtp服務固定的端口是25
EMAIL_PORT = 25
#發送郵件的郵箱
EMAIL_HOST_USER = '[email protected]'
#在郵箱中設置的客戶端授權密碼
EMAIL_HOST_PASSWORD = '009723'
#收件人看到的發件人 <此處要和發送郵件的郵箱相同>
EMAIL_FROM = 'python<[email protected]>'

ADMINS = (
    ('tom', '[email protected]'),
)
# 配置郵件
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
SERVER_EMAIL = EMAIL_HOST_USER

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': '%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(module)s:%(funcName)s] [%(levelname)s]- %(message)s'}
    },
    'filters': {  # 過濾條件
        # 要求debug是False才記錄
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        }
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'logging.NullHandler',
        },
        'mail_admins': {  # 一旦線上代碼報錯 郵件提示
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'filters': ['require_debug_false'],
        },
        'debug': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, "log", 'debug.log'),  # 文件路徑
            'maxBytes': 1024 * 1024 * 5,  # 5兆的數據
            'backupCount': 5,  # 允許有5這樣的文件
            'formatter': 'standard',  # 格式
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'standard',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False
        },
        'django.request': {
            'handlers': ['debug', 'mail_admins'],
            'level': 'ERROR',
            'propagate': True,  # 是否繼承父類的log信息
        },
        # 對於不在 ALLOWED_HOSTS 中的請求不發送報錯郵件
        'django.security.DisallowedHost': {
            'handlers': ['null'],
            'propagate': False,
        },
    }
}

創建log路徑:/log/debug.log

urls

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include("App.urls"))
]

App.urls

from django.urls import path

from App import views
app_name='App'
urlpatterns = [
    # 日誌
    path('log/',views.handle_log, name='log'),
]

App.views

from django.http import HttpResponse

def handle_log(request):
    print(1 / 0)
    return HttpResponse("日誌")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章