Python practiced hand, encapsulated log module, v2

Source: Internet
Author: User
Tags erro

Before the 1th edition is written well, very messy, the main problem is that Python does not support method overloading, want to flexibly create objects, at the time, the workaround is to first chain to selectively set the property (the essence of the method overload is to selectively set the property), then do the instantiation, so that the subsequent creation of the object is very messy.


And then know that Python can default parameters, in disguise to do method overloading


Code: Python3

The # -*- coding: utf-8 -*-'     --encapsulates the logging module, discarding the cumbersome settings, preserving only the key settings and beautifying the output format ' "Import sys,random,time import logging as lgdef getrandomint (digits):      "     @args:          int  digits     @returns:          string      "    return random.randint (1,10**digits-1). __str__ (). Zfill ( digits)  def getnowdate (FMT):     "     @args:          string fmt     @returns:          string     '     return  Time.strftime (Fmt,time.localtime ()). __str__ () Def getoriginpath ():     "      @returns:          string     '     return  sys.argv[0]class xlogger ():         "    The  -logger  -encapsulates the logging module, discarding the cumbersome settings, preserving only the key settings, and beautifying the output format     -approximate usage:-Create Xlogger, add Xhandler                 -for Xlogger                      -allows you to set the log level, logger name, and parent-child recorder's propagation function                  -for xstreamhandler  console output                      -not allow settings                  -for xfilehandler  file output                      -allow set file path, file Write method: Overwrite/Append      ' '         levelmap = {' DEBUG ': Lg. debug,                 ' INFO ': lg.info,                 ' WARN ' : Lg. warning,                 ' ERROR ': Lg. error,                 ' CRITICAL ': Lg. critical}        def __init__ (self,name= ' AUTO ', level= ' INFO ', Propagate=false):         "          @args:              string name    Recorder name   (name can reflect recorderParent-child relationship)             String level  log level   DEBUG/INFO/WARN/ERROR/CRITICAL             String propagate  whether to turn on the parent-child logger's up-propagation function                                 -  if enabled, the child logger will get all the handler,          of the parent logger                       -  be careful to add handler repeatedly to avoid duplicate logs          '          self.level     = level         self.propagate = propagate         if name.upper ()  ==  ' AUTO '  :            self.name =  Getrandomint (        else:      )       self.name = name                         self.logger  = lg.getlogger (self.name)         self.logger.setlevel ( XLogger.levelMap.get (self.level))         self.logger.propagate =  self.propagate            def  AddHandler (Self,xhandler):         self.logger.addhandler ( Xhandler.handler)         return self         def debug (self,layer,message):         self.logger.debug (' dbug  '  +  ' |·· '  * layer +message)             def  info (self,layer,message):         self.logger.info (' INFO  '  +  ' | '  * layer + message)                def warning (self,layer,message):         Self.logger.warning (' warn  '  +  ' | '  * layer + message)                def error (self,layer,message):         Self.logger.error (' erro  '  +  ' | '  * layer + message)         def critical (self, Layer,message):     &Nbsp;   self.logger.critical (' crit  '  +  ' | '  * layer + message)     class XHandler:         def __init__ (self):             self.handler = None             self.formatter = lg. Formatter (' [% (name) s] % (asctime) s % (message) s ', '%y/%m/%d %h:%m:%s ')              class xfilehandler (Xhandler):                 def __init__ (self,file= ' AUTO ', Model= ' W '):             '               @args:                  string file  file path   If set to auto  the log file path is: Origin execution file. Time + random number +xlog                 String model  File Write mode  w overlay  a              '              xlogger.xhandler.__init__ (self)                           self.model = model             if file.upper ()  ==  ' AUTO '  :                 self.file = getoriginpath () + '. ' +getnowdate ("%y%m%d%h%m%s") +getrandomint (4) + ' XLOG '              else:                self.file = file             self.handler = lg. Filehandler (Self.file,mode=self.model.lower (), encoding= ' UTF-8 ', Delay=false)              self.handler.setformatter (Self.formatter)                               class xstreamhandler (Xhandler):                 def __init__ (self):             xlogger.xhandler.__init__ (self)                           self.handler = lg. Streamhandler ()  &nbsP;          self.handler.setformatter (Self.formatter) 

Test:

Dir_= ' d:\\users\\ex-hexuwen001\\desktop\\work\m1-apps\\using__apps_data\\eclipse_workspace\\mypython\\ src ' file1=dir_+ ' \\1.xlog ' file2=dir_+ ' \\2.xlog ' Logger1 = xlogger (name= ' aaaa ',  level= ' DEBUG ',  propagate=true)             .addhandler ( Xlogger.xfilehandler (file=file1, model= ' W '))              .addhandler (Xlogger.xstreamhandler ())              logger1.debug (0, "Cool LAN") logger1.info (1, ' Guangdong Province ') logger1.warning (2, ' Zhaoqing ') logger1.error (2, ' Gaoyao ') Logger1.critical (3, ' Cool Town ') Logger2 = xlogger (name= ' aaaa.bbbb ',  level= ' DEBUG ',  propagate=true )             .addhandler (XLogger.XFileHandler (file =file2, model= ' W '))             .addhandler ( Xlogger.xstreamhandler ())   &Nbsp;         logger2.debug (0, "LAN") logger2.info (1, ' Guangdong Province ') Logger2.warning (2, ' Zhaoqing ') logger2.error (2, ' Gaoyao ') logger2.critical (3, ' the Town ')

Output:

[AAAA] 18/01/12 14:55:04 dbug LAN [AAAA] 18/01/12 14:55:04 INFO | Guangdong province [AAAA] 18/01/12 14:55:04 WARN | | Zhaoqing [AAAA] 18/01/12 14:55:04 Erro | | Gaoyao [AAAA] 18/01/12 14:55:04 crit | | | Niu Zhen [aaaa.bbbb] 18/01/12 14:55:04 dbug LAN [AAAA.BBBB] 18/01/12 14:55:04 dbug LAN [AAAA.BBBB] 18/01/12 14:55:04 INFO |·· Guangdong Province [aaaa.bbbb] 18/01/12 14:55:04 INFO | Guangdong Province [aaaa.bbbb] 18/01/12 14:55:04 WARN | | Zhaoqing [aaaa.bbbb] 18/01/12 14:55:04 WARN | | Zhaoqing [aaaa.bbbb] 18/01/12 14:55:04 Erro | | Gaoyao [aaaa.bbbb] 18/01/12 14:55:04 Erro | | Gaoyao [aaaa.bbbb] 18/01/12 14:55:04 crit | | | Niu Zhen [aaaa.bbbb] 18/01/12 14:55:04 crit | | | Niu Zhen


Python practiced hand, encapsulated log module, v2

Related Article

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.