首页 > 编程 > Python > 正文

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

2019-11-25 12:52:37
字体:
来源:转载
供稿:网友

本文实例讲述了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 logginglogger = 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程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表