Django与mysql和logging

本文详细介绍了在Django项目中如何配置和使用日志系统,包括数据库配置、项目目录结构、日志系统配置及具体应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

1. MYSQL_CONFIG

# MYSQL CONFIG
MYSQL_CONFIG = {
    'ENGINE': 'django.db.backends.mysql',
    'HOST': '192.168.*.*',
    'PORT': '3309',
    'NAME': 'helloworld',
    'USER': 'root',
    'PASSWD': '123456'
}


# Django中mysql信息设置
DATABASES = {
    # 'default': {
    #     # 'ENGINE': 'django.db.backends.sqlite3',
    #     # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    # }
    'default': {
        'ENGINE': MYSQL_CONFIG.get('ENGINE'),
        'HOST': MYSQL_CONFIG.get('HOST'),
        'PORT': MYSQL_CONFIG.get('PORT'),
        'NAME': MYSQL_CONFIG.get('NAME'),
        'USER': MYSQL_CONFIG.get('USER'),
        'PASSWORD': MYSQL_CONFIG.get('PASSWD'),
    }
}

2. helloworld 项目目录结构

E:\dev\helloworld>tree /f
Folder PATH listing for volume 文档
Volume serial number is 00000137 299D:817A
E:.
│  manage.py
│
├─.idea
│      encodings.xml
│      helloworld.iml
│      misc.xml
│      modules.xml
│      workspace.xml
│
├─hello
│  │  admin.py
│  │  apps.py
│  │  models.py
│  │  tests.py
│  │  views.py
│  │  __init__.py
│  │
│  ├─migrations
│  │  │  __init__.py
│  │  │
│  │  └─__pycache__
│  │          __init__.cpython-36.pyc
│  │
│  └─__pycache__
│          admin.cpython-36.pyc
│          apps.cpython-36.pyc
│          models.cpython-36.pyc
│          views.cpython-36.pyc
│          __init__.cpython-36.pyc
│
├─helloworld
│  │  settings.py
│  │  urls.py
│  │  wsgi.py
│  │  __init__.py
│  │
│  └─__pycache__
│          settings.cpython-36.pyc
│          urls.cpython-36.pyc
│          wsgi.cpython-36.pyc
│          __init__.cpython-36.pyc
│
└─templates

3. settings中配置日志系统


# ================ Django logging begin =========================
import logging

LOGGING_DIR = "/logs/helloworld"
if not os.path.exists(LOGGING_DIR):
    os.makedirs(LOGGING_DIR)
    
LOG_LEVEL = 'DEBUG' if DEBUG else 'INFO'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': '[%(levelname)s]-[%(asctime)s]-[%(filename)s]-[%(funcName)s]-[%(lineno)d] >> %(message)s',
        },
        'simple': {
            'format': '[%(funcName)s]-[%(lineno)d] >> %(message)s',
        },
    },
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
        'file_handler': {
            'encoding': 'utf8',
            'level': 'INFO',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'when': 'D',
            'interval': 1,
            'backupCount': 180,
            'filename': '%s/helloworld.log' % LOGGING_DIR,
            'formatter': 'standard',
        },
    },
    'loggers': {
        'hello': {
            'handlers': ['console', 'file_handler'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

# ================ Django logging end ==========================

4. Django中日志使用

4.1 hello/views.py

from django.http import HttpResponse
import logging

def get_logger(name=None):
    return logging.getLogger(name=name)

logger = get_logger('hello')

def hello(request):
    logger.info('this is the hello log for testing.')
    return HttpResponse("Hello World!")

4.2 helloworld/urls.py

from hello.views import hello
from django.conf.urls import url

urlpatterns = [
    path('admin/', admin.site.urls),
    url('hello/', hello),
]

5. 日志使用效果

5.1 浏览器调用

http://127.0.0.1:8009/hello/

5.2 控制台显示

[hello]-[25] >> this is the hello log for testing.

5.3 日志文件显示(/logs/helloworld/helloworld.log)

[INFO]-[2019-12-09 21:27:38,884]-[views.py]-[hello]-[25] >> this is the hello log for testing.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值