Configuration and use of django1.4 log module, and django1.4 Log Module

Source: Internet
Author: User

Configuration and use of django1.4 log module, and django1.4 Log Module
1. Default log Configuration

By default, django 1.4 has a simple log configuration, as shown below:

# 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,        },      }   }

The default 'Disable _ existing_loggers 'value is False.

Formatters is not defined by default.

In the dictionary, no comma is added to the end of the group, so you need to write it when adding the group.

2. Simple Example 1. Configure LOGGING in settings. py

Add the following green content configuration.

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        },    }}

In the configuration, you can customize levels, filename, and so on. You need to configure several handler and logger files.

2. Use
  • Import logging
  • If you want to use the log test1 in view. py of log, write:
    • Log = logging. getLogger ('test1 ')
    • Log. error ()
  • Pass the variable in the log Content, log. error ("Get html error, % s" % (e ))
#! /Usr/bin/python #-*-coding: UTF-8-*-import loggingfrom django. http import HttpResponseRedirect, HttpResponse, Http404from django. shortcuts import render_to_response, get_object_or_404from django. template import RequestContextlog = logging. getLogger ('test1') def getHtml (request, arg): try: url = request. path url = url [1:] return render_to_response (url, RequestContext (request) except t Exception, e: # log. error ("Get html error, % s" % (e) log. error ("log Content") raise Http404

 

The log after using the variable is as follows:

3. encapsulate the django logging Module

The built-in logging module of django can also be used. If you have higher requirements and want to add custom colors and formats, perform the following operations.

1. encapsulate logs into a separate 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. Create a log. py with the following content:
#!/usr/bin/pythonimport osimport sysimport timesys.path.append("..")import confimport loggingimport logging.handlerstry:    import curses    curses.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 = None    def __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=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 is a configuration file that is configured in the same directory as the log app.

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

Add the following test code to the log. py result:

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

The test results are as follows:

4. Use in view
usage e.g:from log import MessageLogLOG = 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, the author of this article, is constantly learning and growing because of the changing knowledge. The content of this article is also updated from time to time. To avoid misleading readers and facilitate tracing, Please repost the Source: Ghost.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.