一、默认日志配置

在django 1.4中默认有一个简单的日志配置,如下

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = { 'version': 1,'disable_existing_loggers': False,'filters': {'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}   },  'handlers': {'mail_admins': {'level': 'ERROR','filters': ['require_debug_false'],'class': 'django.utils.log.AdminEmailHandler'}   },  'loggers': {'django.request': {'handlers': ['mail_admins'],'level': 'ERROR','propagate': True,},  }
}

可以看出默认的‘disable_existing_loggers’值为False。

默认没有定义formatters。

字典中,组结束没有加逗号,所以在增加时需要写上。

二、简单例子

1、配置settings.py中LOGGING

增加下面绿色部分内容配置。

LOGGING = {'version': 1,'disable_existing_loggers': False,'formatters': {'standard': {'format': '%(levelname)s %(asctime)s %(message)s'},},'filters': {'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'},},'handlers': {'mail_admins': {'level': 'ERROR','filters': ['require_debug_false'],'class': 'django.utils.log.AdminEmailHandler'},'test1_handler':{'level':'DEBUG','class':'logging.handlers.RotatingFileHandler','filename':'/yl/smartcloud/smartcloud/lxytest.log','formatter':'standard',},},'loggers': {'django.request': {'handlers': ['mail_admins'],'level': 'ERROR','propagate': True,},'test1':{'handlers':['test1_handler'],'level':'INFO','propagate':False},}
}

配置中level,filename之类的可自定义,需要几个文件就配置几个handler和logger。

2、使用

  • 导入logging
  • 如果在用到log的view.py中,想使用test1这个日志,就写:
    • log=logging.getLogger('test1')
    • log.error()
  • 在日志内容中传递变量,log.error("Get html error, %s" % (e))
#!/usr/bin/python
#-*- coding: UTF-8 -*-import logging
from django.http import HttpResponseRedirect,HttpResponse, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContextlog=logging.getLogger('test1')def getHtml(request,arg):try:url=request.pathurl=url[1:]return render_to_response(url,RequestContext(request))except Exception,e:#log.error("Get html error, %s" % (e))log.error("日志内容")raise Http404

使用变量后的log如下:

三、封装django logging模块

django自带的logging模块也是可以用的,如果要求更高,希望加一些自定义的颜色,格式等,可进行下面操作。

1、将log封装成一个单独的app

[root@yl-web-test log]# django-admin.py startapp log
[root@yl-web-test log]# ls
__init__.py  models.py  tests.py  views.py

2、创建一个log.py,内容如下

#!/usr/bin/pythonimport os
import sys
import time
sys.path.append("..")
import conf
import logging
import logging.handlerstry:import cursescurses.setupterm()
except:curses = Nonedefault_logfile = getattr(conf,'SMARTCLOUD_LOGFILE')class Singleton(type):"""Singleton Metaclass"""def __init__(cls,name,bases,dic):super(Singleton,cls).__init__(name,bases,dic)cls.instance = Nonedef __call__(cls, *args, **kwargs):if cls.instance is None:cls.instance = super(Singleton,cls).__call__(*args,**kwargs)return cls.instanceclass MessageFormatter(logging.Formatter):def __init__(self,color,*args,**kwargs):logging.Formatter.__init__(self,*args,**kwargs)self._color=colorif color and curses:fg_color = unicode(curses.tigetstr("setaf") or\curses.tigetstr("setf") or "", "ascii")self._colors={logging.DEBUG: unicode(curses.tparm(fg_color,2),"ascii"),logging.INFO: unicode(curses.tparm(fg_color,6),"ascii"),logging.WARNING: unicode(curses.tparm(fg_color, 3), "ascii"),logging.ERROR: unicode(curses.tparm(fg_color, 5), "ascii"),logging.FATAL: unicode(curses.tparm(fg_color, 1), "ascii"),}self._normal = unicode(curses.tigetstr("sgr0"), "ascii")def format(self,record):try:record.message = record.getMessage()except Exception, e:record.message = "Bad message (%r): %r" % (e, record.__dict__)record.asctime = time.strftime("%Y/%m/%d %H:%M:%S",\self.converter(record.created))prefix = '[%(levelname)-8s %(asctime)s] ' % record.__dict__if self._color and curses:prefix = (self._colors.get(record.levelno, self._normal) +\prefix + self._normal)formatted = prefix + record.messageif record.exc_info:if not record.exc_text:record.exc_text = self.formatException(record.exc_info)if record.exc_text:formatted = formatted.rstrip() + "\n" + record.exc_textreturn formatted.replace("\n", "\n    ")class MessageLog(object):__metaclass__ = Singletondef __init__(self, logfile=default_logfile,):self._LEVE = {1:logging.INFO, 2:logging.WARNING, 3:logging.ERROR,\4:logging.DEBUG, 5:logging.FATAL}self.loger = logging.getLogger()self._logfile = logfileself.init()def init(self):if not os.path.exists(self._logfile):os.mknod(self._logfile)handler = logging.handlers.RotatingFileHandler(self._logfile)handler.setFormatter(MessageFormatter(color=True))self._handler = handlerself.loger.addHandler(handler)def INFO(self,msg,leve=1):self.loger.setLevel(self._LEVE[leve])self.loger.info(msg)def WARNING(self, msg, leve=2):self.loger.setLevel(self._LEVE[leve])self.loger.warning(msg)def ERROR(self, msg, leve=3):self.loger.setLevel(self._LEVE[leve])self.loger.error(msg)def DEBUG(self, msg, leve=4):self.loger.setLevel(self._LEVE[leve])self.loger.debug(msg)def FATAL(self, msg, leve=5):self.loger.setLevel(self._LEVE[leve])self.loger.fatal(msg)

conf.py是一个配置文件,在log app同目录,里面配置了log文件目录。

import osSMARTCLOUD_LOGFILE='/yl/smartcloud/log/smartcloud.log'

3、测试

在log.py结果加上一段测试代码如下:

if __name__ == "__main__":LOG = MessageLog()str1 = "aaaaaaaa"str2 = "bbbbbbbbbb"LOG.INFO("#%s###################################""@@@@%s@@@@@@@@@@@" %(str1,str2))LOG.WARNING("####################################")LOG.ERROR("####################################")LOG.DEBUG("####################################")LOG.FATAL("####################################")

测试结果如下:

4、在view中使用

usage e.g:from log import MessageLog
LOG = MessageLog('your log file by full path')
or LOG = MessageLog()
default logfile name is '/yl/smartcloud/log/smartcloud.log'LOG.INFO('some message')
LOG.WARNING('some message')
LOG.ERROR('some message')
LOG.DEBUG('some message')
LOG.FATAL('some message')

本文作者starof,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:http://www.cnblogs.com/starof/p/4702026.html有问题欢迎与我讨论,共同进步。

django1.4日志模块配置及使用相关推荐

  1. Django日志模块配置

    django日志模块 日志模块工作流程 产生日志(日志实例) 渲染格式(格式化) 匹配过滤(过滤器) 持久化(处理器) 格式器formatter 关键词 描述 asctime 时间(2018-01-0 ...

  2. python logging日志模块的使用

    1.日志级别 日志一共分成5个等级,从低到高分别是:DEBUG ,INFO, WARNING ,ERROR, CRITICAL. DEBUG:详细的信息,通常只出现在诊断问题上 INFO:确认一切按预 ...

  3. Python之配置日志模块logging

    一.定义日志打印方式 如果我们运行自己的程序,有时候需要记录程序运行过程中出现的问题或者信息.可以运用日志模块logging来记录,该模块日志格式可以根据用户需求来自己定义. 常见打印日志信息形式如下 ...

  4. day31 logging 日志模块

    1 # logging 日志模块 ****** 2 # 记录用户行为或者代码执行过程 3 # print 来回注释比较麻烦的 4 # logging 5 # 我能够"一键"控制 6 ...

  5. [转]ASP.NET 核心模块配置参考

    本文转自:https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/aspnet-core-module?view=aspnetcore ...

  6. python logging模块的作用_Python 日志模块logging分析及使用-2

    本文作为Python日志模块的补充,主要介绍日志回滚RotatingFileHandler和TimedRotatingFileHandler的使用,以及其所带来的问题.Logger对象的日志等级是如何 ...

  7. DPDK — RTE_LOG 日志模块

    目录 文章目录 目录 DPDK 的日志系统 RTE_LOG 宏 rte_log 和 rte_vlog 函数 日志模块初始化 第一阶段初始化 第二阶段初始化 注册新的日志类型 复用现有日志类型 参考文档 ...

  8. python之强大的日志模块

    1.简单的将日志打印到屏幕   import logging logging.debug('This is debug message') logging.info('This is info mes ...

  9. Python的日志模块logging的使用

    Python的日志模块logging的使用 1 logging模块介绍 2 logging 简单示例 3 logging.basicConfig() 4 logging组件 4.1 Logger类 4 ...

最新文章

  1. 一天狂揽2000+星,微软面向初学者ML课程来了,完全免费
  2. linux空洞目录,学习笔记:linux之文件空洞
  3. MAP Protocol 协议(2)介绍二
  4. 《R语言实战》第6章
  5. MySQL 性能 细节 考量 (更新中......)
  6. gitlab 开源项目 星_49必须了解的机器学习开源项目,Github上平均3600星
  7. 最简单的6种防止数据重复提交的方法!(干货)
  8. 21个WordPress店铺必备免费工具
  9. 调查显示超四成人“讨厌”大数据
  10. 在线文本字符串转十六进制工具
  11. switch【耀西的手工世界xic】破解xic文件下载
  12. 人到中年想学一门手艺自己创业好不好
  13. 渗透中POC、EXP、Payload、Shellcode和exploit的区别
  14. 改变蜡笔小新的眼睛颜色(对bmp图像的部分更改)
  15. AR虚拟互动系统创造身临其境的多元互动体验
  16. 前端开发面试问题及答案收录
  17. ospf状态机-通俗易懂的小故事
  18. hashcat跑握手包笔记
  19. 阿里的素质在线测评2020春招Java实习
  20. Xmind思维导图编写测试点,便于扩展测试用例(详细)

热门文章

  1. 解决KeyError: ‘acc‘ 和KeyError: ‘val_acc‘错误
  2. 修改Windows的cmd和PowerShell 的字体
  3. php当前日期的时间戳,php – 获取当前的ISO8601日期/时间戳
  4. c语言const与*位置关系,C语言程序的存储区域与const关键字的使用方法
  5. mysql无法启动无法停止_Centos7以上的版本 mysql 无法启动,无法停止问题
  6. 实战分析 RocketMQ事务消息
  7. Tomcat(一):背景知识和安装tomcat
  8. Java 泛型 T,E,K,V,?,傻傻分不清?
  9. python 余弦_Python快速余弦距离
  10. 你需要知道的有关Selenium异常处理的都在这儿