django1.4日志模块配置及使用
一、默认日志配置
在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 RequestContext log=logging.getLogger('test1') def getHtml(request,arg):
try:
url=request.path
url=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/python import os
import sys
import time
sys.path.append("..")
import conf
import logging
import logging.handlers try:
import curses
curses.setupterm()
except:
curses = None default_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 = None
def __call__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super(Singleton,cls).__call__(*args,**kwargs)
return cls.instance class MessageFormatter(logging.Formatter):
def __init__(self,color,*args,**kwargs):
logging.Formatter.__init__(self,*args,**kwargs)
self._color=color
if 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.message
if 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_text
return formatted.replace("\n", "\n ") class MessageLog(object):
__metaclass__ = Singleton def __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 = logfile
self.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 = handler
self.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 os SMARTCLOUD_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日志模块配置及使用的更多相关文章
- logging日志模块配置
logging日志模块 日志级别 日志一共分成5个等级,从低到高分别是: 1)DEBUG 2)INFO 3)WARNING 4)ERROR 5)CRITICAL 说明: DEBUG:详细的信息,通常只 ...
- python日志模块配置
import logging logging.basicConfig(filename= 'out.log',filemode= 'w+', level= logging.DEBUG, format= ...
- python日志模块
许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系 统的运行状况进行跟踪.在.NET平台中,有非常著名的第三方开源日志组件log4net,c++中,有人们熟悉的log4c ...
- Python日志模块logging用法
1.日志级别 日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRITICAL. DEBUG:详细的信息,通常只出现在诊断问题上 INFO:确认一切按预期运行 ...
- Yii2.0简单隐藏index.php文件和模块配置和layout布局配置禁用和日志写入配置
隐藏index.php文件 目的:想去掉浏览器地址栏中的 index.php?r= 这一块. 在/config/web.php中 ’components'=>[] 中添加如下代码: 'u ...
- logging日志模块、配置字典
logging日志模块 知识点很多 但是需要掌握的很少(会用即可) import logging # 日志有五个等级(从上往下重要程度不一样) # logging.debug('debug级别') # ...
- logging日志模块详细,日志模块的配置字典,第三方模块的下载与使用
logging日志模块详细 简介 用Python写代码的时候,在想看的地方写个print xx 就能在控制台上显示打印信息,这样子就能知道它是什么 了,但是当我需要看大量的地方或者在一个文件中查看的时 ...
- 【腾讯Bugly干货分享】微信mars 的高性能日志模块 xlog
本文来自于腾讯bugly开发者社区,未经作者同意,请勿转载,原文地址:http://dev.qq.com/topic/581c2c46bef1702a2db3ae53 Dev Club 是一个交流移动 ...
- 搭建一套自己实用的.net架构(2)【日志模块-log4net】
先谈谈简单的模块,日志.在系统中日志模块是必须的,什么系统日志,操作日志,调试日志.这里用的是log4net. 对log4net还不熟悉的小伙伴们赶快去搜索基础教程哦, 我这里就不温故了. 那么有人要 ...
随机推荐
- javascript的switch的使用注意
如果是以下代码: <script> var t_keleyi_com = 65; switch (t_keleyi_com) { case '65': alert("字符串65. ...
- 使用ruby搭建简易的http服务和sass环境
使用ruby搭建简易的http服务和sass环境 由于在通常的前端开发情况下,我们会有可能需要一个http服务,当然你可以选择自己写一个node的http服务,也比较简单,比如下面的node代码: v ...
- 自定义easyui整数或者数字、字母或者下划线验证方法
$.extend($.fn.validatebox.defaults.rules, { intOrFloat: {// 验证整数或小数 validator: function (value) { re ...
- python任务执行之线程,进程,与协程
一.线程 线程为程序中执行任务的最小单元,由Threading模块提供了相关操作,线程适合于IO操作密集的情况下使用 #!/usr/bin/env python # -*- coding:utf-8 ...
- git和svn
git 分布式管理工具 svn 集中式管理工具 1. Git是分布式的,SVN是集中式的,好处是跟其他同事不会有太多的冲突,自己写的代码放在自己电脑上,一段时间后再提交.合并,也可以不用联网在本地提交 ...
- HTML <base> 标签 为页面上的所有链接规定默认地址或默认目标
定义和用法 <base> 标签为页面上的所有链接规定默认地址或默认目标. 通常情况下,浏览器会从当前文档的 URL 中提取相应的元素来填写相对 URL 中的空白. 使用 <base& ...
- react native 的js 文件从哪里获取
/** * Loading JavaScript code - uncomment the one you want. * * OPTION 1 * Load from development ser ...
- ubuntu 安装 swoole 和mac 安装swoole 扩展
ubuntu php 安装swoole 比较容易 1. 从git下载源码 2. 下载pcre http://sourceforge.net/projects/pcre/files/pcre/8.36/ ...
- APNS远程推送(转发)
/*****************************************2************************************************/ /****** ...
- RDVTabBarController的基本使用 以及tabbar的防止双点击方法
RDVTabBarController这个库写得相当不错,所以今天就简单介绍下它的基本使用,看里面可以清楚的知道代码规范的重要性,这个库的使用方法和官方的相识 下载地址:https://github. ...