Python Django框架实现应用添加logging日志操作示例

yipeiwu_com6年前Python基础

本文实例讲述了Python Django框架实现应用添加logging日志。分享给大家供大家参考,具体如下:

Django uses Python's builtin logging module to perform system logging.

Django使用python的内建日志模块来记录系统日志,但是要想在django应用中开启此功能使我们的部分操作能够被记录到日志文件,那么就需要进行一定的配置并且根据具体的log类型来进行调用

step 1:配置setting.py

以下配置除了filename和formatters需要根据实际情况来修改外都可以保持不变

LOGGING = {
  'version': 1,
  'disable_existing_loggers': False,#此选项开启表示禁用部分日志,不建议设置为True
  'formatters': {
    'verbose': {
      'format': '%(levelname)s %(asctime)s %(message)s'#日志格式
    },
    'simple': {
      'format': '%(levelname)s %(message)s'
    },
  },
  'filters': {
    'require_debug_true': {
      '()': 'django.utils.log.RequireDebugTrue',#过滤器,只有当setting的DEBUG = True时生效
    },
  },
  'handlers': {
    'console': {
      'level': 'DEBUG',
      'filters': ['require_debug_true'],
      'class': 'logging.StreamHandler',
      'formatter': 'verbose'
    },
    'file': {#重点配置部分
      'level': 'DEBUG',
      'class': 'logging.FileHandler',
      'filename': '/home/lockey23/myapp/myapp/debug.log',#日志保存文件
      'formatter': 'verbose'#日志格式,与上边的设置对应选择
        }
  },
  'loggers': {
    'django': {#日志记录器
      'handlers': ['file'],
      'level': 'DEBUG',
      'propagate': True,
    }
  },
}

step 2: 实际调用

比如说我们想在某些view中调用logger来记录操作,如下:

import logging
logger = logging.getLogger('django')#这里的日志记录器要和setting中的loggers选项对应,不能随意给参
#接下来就是调用了:
logger.debug('[Debug] '+ msg)
logger.info('[Success] '+ msg)
logger.warning('[Warning] '+ msg)
logger.error('[Error] '+ msg)
logger.critical('[Critical] '+ msg)
......
if auth_pass:
  logger.info('[Success] '+ user +' has logged in!')
  return JsonResponse({'result': 'Success', 'message': 'Login successfully.'})
else:
  logger.warning('[Failed] '+ user + ' failed to login!')

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

相关文章

Flask中endpoint的理解(小结)

在flask框架中,我们经常会遇到endpoint这个东西,最开始也没法理解这个到底是做什么的。最近正好在研究Flask的源码,也就顺带了解了一下这个endpoint 首先,我们看一个...

使用python遍历指定城市的一周气温

处于兴趣,写了一个遍历指定城市五天内的天气预报,并转为华氏度显示。 把城市名字写到一个列表里这样可以方便的添加城市。并附有详细注释 import requests import js...

python 实现手机自动拨打电话的方法(通话压力测试)

现在能用自动化实现的,尽量使用自动化程序去操作,代替人工去操作,更有效率。 今天说下用python结合adb命令去实现安卓手机端的通话压力测试。 #操作前先在设置里打开power键可...

python将excel转换为csv的代码方法总结

python:如何将excel文件转化成CSV格式 import pandas as pd data = pd.read_excel('123.xls','Sheet1',index...

python实现word 2007文档转换为pdf文件

在开发过程中,会遇到在命令行下将DOC文档(或者是其他Office文档)转换为PDF的要求。比如在项目中如果手册是DOC格式的,在项目发布时希望将其转换为PDF格式,并且保留DOC中的书...