Python Log Object

Source: Internet
Author: User

A test interface log module was written:

Import Loggingclass log:def __init__ (self,filename,level= "INFO"): Print ("Start") self.filename=filename Self.level=level Self.logger=logging.getlogger () #得到logger实体 self.logger.setLevel (logging. DEBUG) #设置日志最低输出级别默认为WARN self.formatter=logging. Formatter ("[% (asctime) s-% (filename) s]-% (levelname) s:% (message) S") #设置日志格式 def __createhandler (self): #创建Fil Ehandler, log input to file fh=logging. Filehandler (Self.filename, ' a ') fh.setlevel (logging. DEBUG) Fh.setformatter (self.formatter) Self.logger.addHandler (FH) # Create Filehandler, log input to console CH = Logging. Streamhandler () Ch.setlevel (logging. DEBUG) Ch.setformatter (self.formatter) self.logger.addHandler (CH) return fh,ch def __console (self,            Message): if Self.level = = "INFO": self.logger.info (message) if Self.level = = "DEBUG": Self.logger.debug (message) if Self.level = = "WARN": SELF.LOgger.warn (message) if Self.level = = "ERROR": Self.logger.error (Message) def __call__ (SELF,FUC):                def wrapper (*args,**kwargs): FH, Ch=self.__createhandler () for I in range (len (args)): Self.__console (Args[i]) Self.logger.removeHandler (FH) Self.logger.removeHandler (CH) F UC (*args, **kwargs) return wrapper# test code filename= "Test.log" url= "http://192.168.100.34:8325/business/metadata/city/ Get "way=" get "header=" {' Hyaline-auth-accessheader ': {' syscode ': ' che001 '} ' params= ' {' Code ': U ' 04986580 '} ' @Log ( Filename,level= "INFO") def writelog (url,way,header,params): Print ("Other operations") Writelog (Url,way,header,params)

1.getLogger (): This is the most basic entrance, the method parameter can be empty, the default logger name is root, if the same program has been using the same name of logger, actually will get the same instance, Using this technique, you can invoke the same logger across modules to log logs.

The 2.Formatter object defines the structure and contents of the log information and requires two parameters to be constructed:

    • One is a formatted template fmt that contains the most basic level and information by default. message
    • One is the formatted time style datefmt , which defaults to2003-07-08 16:49:45,896 (%Y-%m-%d %H:%M:%S)

fmtYou can refer to the following table for the variables allowed in the

  • % (name) s Logger name
  • % (levelno) s log level in digital form
  • % (levelname) s log level in text form
  • % (pathname) s calls the full pathname of the module of the log output function and may not have
  • % (filename) s The file name of the module that called the log output function
  • % (module) s call the module name of the log output function |
  • % (funcName) s call the function name of the log output function |
  • % (Lineno) d the line of code where the statement of the log output function is called
  • % (created) F current time, represented by the UNIX standard floating-point number representing Time |
  • % (relativecreated) d When output log information, the number of milliseconds since logger was created |
  • % (asctime) s the current time in string form. The default format is "2003-07-08 16:49:45,896". The comma is followed by milliseconds
  • % (thread) d thread ID. Probably not.
  • % (threadname) s thread name. Probably not.
  • % (process) d process ID. Probably not.
  • % (message) s user output message logging has the following levels: Debug,info,warning,error,critical

3.SetLevel The default level is that the Warning,logging module will only output logs above the specified levels. The advantage of this is that in the development of the project debug log, in the product release phase without one by one comments, only need to adjust the level of logger can be, very convenient.

4. The most commonly used Handler are Streamhandler and Filehandler, Handler used to log logs to different output ends.

Logging contains many handler, which may be used in the following types of

    • Streamhandler Instances send error messages to Streams (File-like objects).
    • Filehandler Instances send error messages to disk files.
    • Rotatingfilehandler Instances send error messages to disk files, with support for maximum log file sizes and log File rotation.
    • Timedrotatingfilehandler Instances send error messages to disk files, rotating the log file at certain timed inte Rvals.
    • Sockethandler Instances send error messages to TCP/IP sockets.
    • Datagramhandler Instances send error messages to UDP sockets.
    • Smtphandler Instances send error messages to a designated email address.

Python Log Object

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.