django management commands 设置 log

本文介绍如何配置Django应用程序,在管理命令出现错误时通过电子邮件通知管理员。通过设置LOGGING配置,利用mail_admins处理器发送错误报告,并使用自定义管理命令处理异常。

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

setting.py

LOGGING = {
    #OTHER OPTIONS
    'filters': {
        #OTHER FILTERS
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        #OTHER HANDLERS
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True
        }
    },
    'loggers': {
        #OTHER LOGGERS
        'management_commands': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

 

command

from django.utils.log import getLogger
from django.core.management.base import BaseCommand
import sys

logger = getLogger('management_commands')

class Command(BaseCommand):
    def handle(self, *args, **options):
        try:
            #DO YOUR STUFF HERE
        except Exception as e:
            logger.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
            #Raise the exception again so it gets logged in standard error also.
            raise e

 

 

参考:https://mpcabd.xyz/make-django-management-commands-send-errors-email-admins/

转载于:https://my.oschina.net/sukai/blog/708764

### 创建和使用Django自定义管理命令 #### 文件结构设置 为了创建自定义管理命令,在应用(app)内部需构建特定的文件夹结构。具体来说,应在应用程序目录下建立`management`文件夹,并在其内部进一步创建名为`commands`的子文件夹[^3]。 ```plaintext your_app/ ├── __init__.py ├── models.py └── management/ ├── __init__.py └── commands/ ├── __init__.py └── your_command.py # 自定义命令的具体实现文件 ``` 此结构确保了Django能够识别并加载这些自定义命令。 #### 编写自定义命令代码 在`commands`文件夹中的Python文件里编写具体的命令逻辑。每一个`.py`文件代表了一个独立的命令,其命名即为将来通过`manage.py`调用时使用的命令名称[^4]。下面是一个简单的例子来展示如何在一个叫做`send_dingtalk_notification.py`的文件中实现向钉钉发送消息的功能: ```python from django.core.management.base import BaseCommand, CommandError import requests class Command(BaseCommand): help = 'Sends a message to DingTalk' def add_arguments(self, parser): parser.add_argument('message', type=str) def handle(self, *args, **options): webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=YOUR_ACCESS_TOKEN" headers = {'Content-Type': 'application/json'} data = {"msgtype": "text", "text": {"content": options['message']}} response = requests.post(webhook_url, json=data, headers=headers) if response.status_code != 200 or not response.json().get('success'): raise CommandError(f'Failed to send notification: {response.text}') self.stdout.write(self.style.SUCCESS('Successfully sent the notification')) ``` 这段代码展示了如何利用Django内置类`BaseCommand`快速搭建起一个可执行的任务,同时支持传递参数给命令[^1]。 #### 调用自定义命令 一旦上述步骤完成,就可以通过运行如下命令行指令来触发新创建的命令: ```bash python manage.py send_dingtalk_notification "This is test message." ``` 这将会按照之前编写的逻辑尝试向指定的钉钉群组发送一条测试性质的消息[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值