怎么在Django中配置日志實(shí)現(xiàn)按日期滾動(dòng)?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問題。
修改配置文件
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[%(asctime)s] [%(levelname)s] %(message)s' }, }, 'handlers': { # 輸出日志的控制臺(tái) 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, # 輸出日志到文件,按日期滾動(dòng) 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', # TimedRotatingFileHandler的參數(shù) # 參照https://docs.python.org/3/library/logging.handlers.html#timedrotatingfilehandler # 目前設(shè)定每天一個(gè)日志文件 'filename': 'logs/manage.log', 'when': 'midnight', 'interval': 1, 'backupCount': 100, 'formatter': 'verbose' }, # 發(fā)送郵件,目前騰訊云、阿里云的服務(wù)器對(duì)外發(fā)送郵件都有限制,暫時(shí)不使用 'email': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html': True, } }, 'loggers': { # 不同的logger 'django': { 'handlers': ['console', 'file'], 'level': 'INFO', 'propagate': True, }, }, }
創(chuàng)建logs目錄
cd django_logs/ mkdir logs
新增django_logs/logger.py
import logging logger = logging.getLogger('django')
驗(yàn)證
創(chuàng)建app
python manage.py startapp app
編寫視圖函數(shù)
編寫一個(gè)視圖函數(shù),使用logger用于往日志文件寫入日志
django_logs/app/views.py
from logger import logger from django.shortcuts import HttpResponse def test_logger(request): logger.info('test log') return HttpResponse('test log')
配置Url
django_logs/proj/urls.py
from app import views from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('test_log/', views.test_logger), ]
調(diào)用
訪問 http://127.0.0.1:8000/test_log/ ,在logs/manage.log中成功寫入
[2018-05-18 08:35:44,317] [INFO] test log [2018-05-18 08:35:44,318] [INFO] "GET /test_log/ HTTP/1.1" 200 8
最后,修改系統(tǒng)日期,可以看到日志文件會(huì)按天進(jìn)行分割。
日志寫入僅僅對(duì)于創(chuàng)建的logger對(duì)象有效,如果需要使用logging直接寫入,則需要再做一些修改:讓logging模塊使用django的dictConfig。
import logging.config from django.conf import settings logger = logging.getLogger('django') logging.config.dictConfig(settings.LOGGING)
看完上述內(nèi)容,你們掌握怎么在Django中配置日志實(shí)現(xiàn)按日期滾動(dòng)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
本文名稱:怎么在Django中配置日志實(shí)現(xiàn)按日期滾動(dòng)-創(chuàng)新互聯(lián)
URL網(wǎng)址:http://vcdvsql.cn/article10/dehjdo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、網(wǎng)站營(yíng)銷、自適應(yīng)網(wǎng)站、動(dòng)態(tài)網(wǎng)站、網(wǎng)站改版、靜態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容