Python之logging模块学习(十八)

在很多的时候,我们需要记录下log来方便跟踪下我们的程序,这样的好处是程序在执行的时候,我们不可能

人为的去盯着程序执行,很多的时候,程序执行是一个自动化的过程,那么这中间执行出问题了,我们如何定位

依据是什么,当然定位的方式是有很多的,比如说是打断点,查看log也是一种方式,今天主要来看logging模块的

应用。我们知道,查看一个模块有哪些方法使用的是dir(),查看该模块的详细信息,使用的是help()方法,那么我

们首先来看该模块具备哪些方法以及详细的信息:

复制代码
#!/usr/bin/env python 
#-*- coding:utf-8 -*-

import  logging

dir(logging)
type(help(logging))
复制代码

 

查看如上代码执行后输出的信息:

复制代码
C:\Python27\python.exe D:/git/Python/FullStack/Day10/logIndex.py
Help on package logging:

NAME
    logging

FILE
    c:\python27\lib\logging\__init__.py

DESCRIPTION
    Logging package for Python. Based on PEP 282 and comments thereto in
    comp.lang.python.
    
    Copyright (C) 2001-2014 Vinay Sajip. All Rights Reserved.
    
    To use, simply 'import logging' and log away!

PACKAGE CONTENTS
    config
    handlers

CLASSES
    __builtin__.object
        BufferingFormatter
        Filter
        Formatter
        LogRecord
        LoggerAdapter
    Filterer(__builtin__.object)
        Handler
            NullHandler
            StreamHandler
                FileHandler
        Logger
    
    class BufferingFormatter(__builtin__.object)
     |  A formatter suitable for formatting a number of records.
     |  
     |  Methods defined here:
     |  
     |  __init__(self, linefmt=None)
     |      Optionally specify a formatter which will be used to format each
     |      individual record.
     |  
     |  format(self, records)
     |      Format the specified records and return the result as a string.
     |  
     |  formatFooter(self, records)
     |      Return the footer string for the specified records.
     |  
     |  formatHeader(self, records)
     |      Return the header string for the specified records.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    class FileHandler(StreamHandler)
     |  A handler class which writes formatted logging records to disk files.
     |  
     |  Method resolution order:
     |      FileHandler
     |      StreamHandler
     |      Handler
     |      Filterer
     |      __builtin__.object
     |  
     |  Methods defined here:
     |  
     |  __init__(self, filename, mode='a', encoding=None, delay=0)
     |      Open the specified file and use it as the stream for logging.
     |  
     |  close(self)
     |      Closes the stream.
     |  
     |  emit(self, record)
     |      Emit a record.
     |      
     |      If the stream was not opened because 'delay' was specified in the
     |      constructor, open it before calling the superclass's emit.
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from StreamHandler:
     |  
     |  flush(self)
     |      Flushes the stream.
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from Handler:
     |  
     |  acquire(self)
     |      Acquire the I/O thread lock.
     |  
     |  createLock(self)
     |      Acquire a thread lock for serializing access to the underlying I/O.
     |  
     |  format(self, record)
     |      Format the specified record.
     |      
     |      If a formatter is set, use it. Otherwise, use the default formatter
     |      for the module.
     |  
     |  get_name(self)
     |  
     |  handle(self, record)
     |      Conditionally emit the specified logging record.
     |      
     |      Emission depends on filters which may have been added to the handler.
     |      Wrap the actual emission of the record with acquisition/release of
     |      the I/O thread lock. Returns whether the filter passed the record for
     |      emission.
     |  
     |  handleError(self, record)
     |      Handle errors which occur during an emit() call.
     |      
     |      This method should be called from handlers when an exception is
     |      encountered during an emit() call. If raiseExceptions is false,
     |      exceptions get silently ignored. This is what is mostly wanted
     |      for a logging system - most users will not care about errors in
     |      the logging system, they are more interested in application errors.
     |      You could, however, replace this with a custom handler if you wish.
     |      The record which was being processed is passed in to this method.
     |  
     |  release(self)
     |      Release the I/O thread lock.
     |  
     |  setFormatter(self, fmt)
     |      Set the formatter for this handler.
     |  
     |  setLevel(self, level)
     |      Set the logging level of this handler.
     |  
     |  set_name(self, name)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from Handler:
     |  
     |  name
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from Filterer:
     |  
     |  addFilter(self, filter)
     |      Add the specified filter to this handler.
     |  
     |  filter(self, record)
     |      Determine if a record is loggable by consulting all the filters.
     |      
     |      The default is to allow the record to be logged; any filter can veto
     |      this and the record is then dropped. Returns a zero value if a record
     |      is to be dropped, else non-zero.
     |  
     |  removeFilter(self, filter)
     |      Remove the specified filter from this handler.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from Filterer:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    class Filter(__builtin__.object)
     |  Filter instances are used to perform arbitrary filtering of LogRecords.
     |  
     |  Loggers and Handlers can optionally use Filter instances to filter
     |  records as desired. The base filter class only allows events which are
     |  below a certain point in the logger hierarchy. For example, a filter
     |  initialized with "A.B" will allow events logged by loggers "A.B",
     |  "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
     |  initialized with the empty string, all events are passed.
     |  
     |  Methods defined here:
     |  
     |  __init__(self, name='')
     |      Initialize a filter.
     |      
     |      Initialize with the name of the logger which, together with its
     |      children, will have its events allowed through the filter. If no
     |      name is specified, allow every event.
     |  
     |  filter(self, record)
     |      Determine if the specified record is to be logged.
     |      
     |      Is the specified record to be logged? Returns 0 for no, nonzero for
     |      yes. If deemed appropriate, the record may be modified in-place.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    class Formatter(__builtin__.object)
     |  Formatter instances are used to convert a LogRecord to text.
     |  
     |  Formatters need to know how a LogRecord is constructed. They are
     |  responsible for converting a LogRecord to (usually) a string which can
     |  be interpreted by either a human or an external system. The base Formatter
     |  allows a formatting string to be specified. If none is supplied, the
     |  default value of "%s(message)\n" is used.
     |  
     |  The Formatter can be initialized with a format string which makes use of
     |  knowledge of the LogRecord attributes - e.g. the default value mentioned
     |  above makes use of the fact that the user's message and arguments are pre-
     |  formatted into a LogRecord's message attribute. Currently, the useful
     |  attributes in a LogRecord are described by:
     |  
     |  %(name)s            Name of the logger (logging channel)
     |  %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
     |                      WARNING, ERROR, CRITICAL)
     |  %(levelname)s       Text logging level for the message ("DEBUG", "INFO",
     |                      "WARNING", "ERROR", "CRITICAL")
     |  %(pathname)s        Full pathname of the source file where the logging
     |                      call was issued (if available)
     |  %(filename)s        Filename portion of pathname
     |  %(module)s          Module (name portion of filename)
     |  %(lineno)d          Source line number where the logging call was issued
     |                      (if available)
     |  %(funcName)s        Function name
     |  %(created)f         Time when the LogRecord was created (time.time()
     |                      return value)
     |  %(asctime)s         Textual time when the LogRecord was created
     |  %(msecs)d           Millisecond portion of the creation time
     |  %(relativeCreated)d Time in milliseconds when the LogRecord was created,
     |                      relative to the time the logging module was loaded
     |                      (typically at application startup time)
     |  %(thread)d          Thread ID (if available)
     |  %(threadName)s      Thread name (if available)
     |  %(process)d         Process ID (if available)
     |  %(message)s         The result of record.getMessage(), computed just as
     |                      the record is emitted
     |  
     |  Methods defined here:
     |  
     |  __init__(self, fmt=None, datefmt=None)
     |      Initialize the formatter with specified format strings.
     |      
     |      Initialize the formatter either with the specified format string, or a
     |      default as described above. Allow for specialized date formatting with
     |      the optional datefmt argument (if omitted, you get the ISO8601 format).
     |  
     |  format(self, record)
     |      Format the specified record as text.
     |      
     |      The record's attribute dictionary is used as the operand to a
     |      string formatting operation which yields the returned string.
     |      Before formatting the dictionary, a couple of preparatory steps
     |      are carried out. The message attribute of the record is computed
     |      using LogRecord.getMessage(). If the formatting string uses the
     |      time (as determined by a call to usesTime(), formatTime() is
     |      called to format the event time. If there is exception information,
     |      it is formatted using formatException() and appended to the message.
     |  
     |  formatException(self, ei)
     |      Format and return the specified exception information as a string.
     |      
     |      This default implementation just uses
     |      traceback.print_exception()
     |  
     |  formatTime(self, record, datefmt=None)
     |      Return the creation time of the specified LogRecord as formatted text.
     |      
     |      This method should be called from format() by a formatter which
     |      wants to make use of a formatted time. This method can be overridden
     |      in formatters to provide for any specific requirement, but the
     |      basic behaviour is as follows: if datefmt (a string) is specified,
     |      it is used with time.strftime() to format the creation time of the
     |      record. Otherwise, the ISO8601 format is used. The resulting
     |      string is returned. This function uses a user-configurable function
     |      to convert the creation time to a tuple. By default, time.localtime()
     |      is used; to change this for a particular formatter instance, set the
     |      'converter' attribute to a function with the same signature as
     |      time.localtime() or time.gmtime(). To change it for all formatters,
     |      for example if you want all logging times to be shown in GMT,
     |      set the 'converter' attribute in the Formatter class.
     |  
     |  usesTime(self)
     |      Check if the format uses the creation time of the record.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  converter = <built-in function localtime>
     |      localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
     |                                tm_sec,tm_wday,tm_yday,tm_isdst)
     |      
     |      Convert seconds since the Epoch to a time tuple expressing local time.
     |      When 'seconds' is not passed in, convert the current time instead.
    
    class Handler(Filterer)
     |  Handler instances dispatch logging events to specific destinations.
     |  
     |  The base handler class. Acts as a placeholder which defines the Handler
     |  interface. Handlers can optionally use Formatter instances to format
     |  records as desired. By default, no formatter is specified; in this case,
     |  the 'raw' message as determined by record.message is logged.
     |  
     |  Method resolution order:
     |      Handler
     |      Filterer
     |      __builtin__.object
     |  
     |  Methods defined here:
     |  
     |  __init__(self, level=0)
     |      Initializes the instance - basically setting the formatter to None
     |      and the filter list to empty.
     |  
     |  acquire(self)
     |      Acquire the I/O thread lock.
     |  
     |  close(self)
     |      Tidy up any resources used by the handler.
     |      
     |      This version removes the handler from an internal map of handlers,
     |      _handlers, which is used for handler lookup by name. Subclasses
     |      should ensure that this gets called from overridden close()
     |      methods.
     |  
     |  createLock(self)
     |      Acquire a thread lock for serializing access to the underlying I/O.
     |  
     |  emit(self, record)
     |      Do whatever it takes to actually log the specified logging record.
     |      
     |      This version is intended to be implemented by subclasses and so
     |      raises a NotImplementedError.
     |  
     |  flush(self)
     |      Ensure all logging output has been flushed.
     |      
     |      This version does nothing and is intended to be implemented by
     |      subclasses.
     |  
     |  format(self, record)
     |      Format the specified record.
     |      
     |      If a formatter is set, use it. Otherwise, use the default formatter
     |      for the module.
     |  
     |  get_name(self)
     |  
     |  handle(self, record)
     |      Conditionally emit the specified logging record.
     |      
     |      Emission depends on filters which may have been added to the handler.
     |      Wrap the actual emission of the record with acquisition/release of
     |      the I/O thread lock. Returns whether the filter passed the record for
     |      emission.
     |  
     |  handleError(self, record)
     |      Handle errors which occur during an emit() call.
     |      
     |      This method should be called from handlers when an exception is
     |      encountered during an emit() call. If raiseExceptions is false,
     |      exceptions get silently ignored. This is what is mostly wanted
     |      for a logging system - most users will not care about errors in
     |      the logging system, they are more interested in application errors.
     |      You could, however, replace this with a custom handler if you wish.
     |      The record which was being processed is passed in to this method.
     |  
     |  release(self)
     |      Release the I/O thread lock.
     |  
     |  setFormatter(self, fmt)
     |      Set the formatter for this handler.
     |  
     |  setLevel(self, level)
     |      Set the logging level of this handler.
     |  
     |  set_name(self, name)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  name
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from Filterer:
     |  
     |  addFilter(self, filter)
     |      Add the specified filter to this handler.
     |  
     |  filter(self, record)
     |      Determine if a record is loggable by consulting all the filters.
     |      
     |      The default is to allow the record to be logged; any filter can veto
     |      this and the record is then dropped. Returns a zero value if a record
     |      is to be dropped, else non-zero.
     |  
     |  removeFilter(self, filter)
     |      Remove the specified filter from this handler.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from Filterer:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    class LogRecord(__builtin__.object)
     |  A LogRecord instance represents an event being logged.
     |  
     |  LogRecord instances are created every time something is logged. They
     |  contain all the information pertinent to the event being logged. The
     |  main information passed in is in msg and args, which are combined
     |  using str(msg) % args to create the message field of the record. The
     |  record also includes information such as when the record was created,
     |  the source line where the logging call was made, and any exception
     |  information to be logged.
     |  
     |  Methods defined here:
     |  
     |  __init__(self, name, level, pathname, lineno, msg, args, exc_info, func=None)
     |      Initialize a logging record with interesting information.
     |  
     |  __str__(self)
     |  
     |  getMessage(self)
     |      Return the message for this LogRecord.
     |      
     |      Return the message for this LogRecord after merging any user-supplied
     |      arguments with the message.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    class Logger(Filterer)
     |  Instances of the Logger class represent a single logging channel. A
     |  "logging channel" indicates an area of an application. Exactly how an
     |  "area" is defined is up to the application developer. Since an
     |  application can have any number of areas, logging channels are identified
     |  by a unique string. Application areas can be nested (e.g. an area
     |  of "input processing" might include sub-areas "read CSV files", "read
     |  XLS files" and "read Gnumeric files"). To cater for this natural nesting,
     |  channel names are organized into a namespace hierarchy where levels are
     |  separated by periods, much like the Java or Python package namespace. So
     |  in the instance given above, channel names might be "input" for the upper
     |  level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
     |  There is no arbitrary limit to the depth of nesting.
     |  
     |  Method resolution order:
     |      Logger
     |      Filterer
     |      __builtin__.object
     |  
     |  Methods defined here:
     |  
     |  __init__(self, name, level=0)
     |      Initialize the logger with a name and an optional level.
     |  
     |  addHandler(self, hdlr)
     |      Add the specified handler to this logger.
     |  
     |  callHandlers(self, record)
     |      Pass a record to all relevant handlers.
     |      
     |      Loop through all handlers for this logger and its parents in the
     |      logger hierarchy. If no handler was found, output a one-off error
     |      message to sys.stderr. Stop searching up the hierarchy whenever a
     |      logger with the "propagate" attribute set to zero is found - that
     |      will be the last logger whose handlers are called.
     |  
     |  critical(self, msg, *args, **kwargs)
     |      Log 'msg % args' with severity 'CRITICAL'.
     |      
     |      To pass exception information, use the keyword argument exc_info with
     |      a true value, e.g.
     |      
     |      logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
     |  
     |  debug(self, msg, *args, **kwargs)
     |      Log 'msg % args' with severity 'DEBUG'.
     |      
     |      To pass exception information, use the keyword argument exc_info with
     |      a true value, e.g.
     |      
     |      logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
     |  
     |  error(self, msg, *args, **kwargs)
     |      Log 'msg % args' with severity 'ERROR'.
     |      
     |      To pass exception information, use the keyword argument exc_info with
     |      a true value, e.g.
     |      
     |      logger.error("Houston, we have a %s", "major problem", exc_info=1)
     |  
     |  exception(self, msg, *args, **kwargs)
     |      Convenience method for logging an ERROR with exception information.
     |  
     |  fatal = critical(self, msg, *args, **kwargs)
     |  
     |  findCaller(self)
     |      Find the stack frame of the caller so that we can note the source
     |      file name, line number and function name.
     |  
     |  getChild(self, suffix)
     |      Get a logger which is a descendant to this one.
     |      
     |      This is a convenience method, such that
     |      
     |      logging.getLogger('abc').getChild('def.ghi')
     |      
     |      is the same as
     |      
     |      logging.getLogger('abc.def.ghi')
     |      
     |      It's useful, for example, when the parent logger is named using
     |      __name__ rather than a literal string.
     |  
     |  getEffectiveLevel(self)
     |      Get the effective level for this logger.
     |      
     |      Loop through this logger and its parents in the logger hierarchy,
     |      looking for a non-zero logging level. Return the first one found.
     |  
     |  handle(self, record)
     |      Call the handlers for the specified record.
     |      
     |      This method is used for unpickled records received from a socket, as
     |      well as those created locally. Logger-level filtering is applied.
     |  
     |  info(self, msg, *args, **kwargs)
     |      Log 'msg % args' with severity 'INFO'.
     |      
     |      To pass exception information, use the keyword argument exc_info with
     |      a true value, e.g.
     |      
     |      logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
     |  
     |  isEnabledFor(self, level)
     |      Is this logger enabled for level 'level'?
     |  
     |  log(self, level, msg, *args, **kwargs)
     |      Log 'msg % args' with the integer severity 'level'.
     |      
     |      To pass exception information, use the keyword argument exc_info with
     |      a true value, e.g.
     |      
     |      logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
     |  
     |  makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None)
     |      A factory method which can be overridden in subclasses to create
     |      specialized LogRecords.
     |  
     |  removeHandler(self, hdlr)
     |      Remove the specified handler from this logger.
     |  
     |  setLevel(self, level)
     |      Set the logging level of this logger.
     |  
     |  warn = warning(self, msg, *args, **kwargs)
     |  
     |  warning(self, msg, *args, **kwargs)
     |      Log 'msg % args' with severity 'WARNING'.
     |      
     |      To pass exception information, use the keyword argument exc_info with
     |      a true value, e.g.
     |      
     |      logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  manager = <logging.Manager object>
     |  
     |  root = <logging.RootLogger object>
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from Filterer:
     |  
     |  addFilter(self, filter)
     |      Add the specified filter to this handler.
     |  
     |  filter(self, record)
     |      Determine if a record is loggable by consulting all the filters.
     |      
     |      The default is to allow the record to be logged; any filter can veto
     |      this and the record is then dropped. Returns a zero value if a record
     |      is to be dropped, else non-zero.
     |  
     |  removeFilter(self, filter)
     |      Remove the specified filter from this handler.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from Filterer:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    class LoggerAdapter(__builtin__.object)
     |  An adapter for loggers which makes it easier to specify contextual
     |  information in logging output.
     |  
     |  Methods defined here:
     |  
     |  __init__(self, logger, extra)
     |      Initialize the adapter with a logger and a dict-like object which
     |      provides contextual information. This constructor signature allows
     |      easy stacking of LoggerAdapters, if so desired.
     |      
     |      You can effectively pass keyword arguments as shown in the
     |      following example:
     |      
     |      adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
     |  
     |  critical(self, msg, *args, **kwargs)
     |      Delegate a critical call to the underlying logger, after adding
     |      contextual information from this adapter instance.
     |  
     |  debug(self, msg, *args, **kwargs)
     |      Delegate a debug call to the underlying logger, after adding
     |      contextual information from this adapter instance.
     |  
     |  error(self, msg, *args, **kwargs)
     |      Delegate an error call to the underlying logger, after adding
     |      contextual information from this adapter instance.
     |  
     |  exception(self, msg, *args, **kwargs)
     |      Delegate an exception call to the underlying logger, after adding
     |      contextual information from this adapter instance.
     |  
     |  info(self, msg, *args, **kwargs)
     |      Delegate an info call to the underlying logger, after adding
     |      contextual information from this adapter instance.
     |  
     |  isEnabledFor(self, level)
     |      See if the underlying logger is enabled for the specified level.
     |  
     |  log(self, level, msg, *args, **kwargs)
     |      Delegate a log call to the underlying logger, after adding
     |      contextual information from this adapter instance.
     |  
     |  process(self, msg, kwargs)
     |      Process the logging message and keyword arguments passed in to
     |      a logging call to insert contextual information. You can either
     |      manipulate the message itself, the keyword args or both. Return
     |      the message and kwargs modified (or not) to suit your needs.
     |      
     |      Normally, you'll only need to override this one method in a
     |      LoggerAdapter subclass for your specific needs.
     |  
     |  warning(self, msg, *args, **kwargs)
     |      Delegate a warning call to the underlying logger, after adding
     |      contextual information from this adapter instance.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    class NullHandler(Handler)
     |  This handler does nothing. It's intended to be used to avoid the
     |  "No handlers could be found for logger XXX" one-off warning. This is
     |  important for library code, which may contain code to log events. If a user
     |  of the library does not configure logging, the one-off warning might be
     |  produced; to avoid this, the library developer simply needs to instantiate
     |  a NullHandler and add it to the top-level logger of the library module or
     |  package.
     |  
     |  Method resolution order:
     |      NullHandler
     |      Handler
     |      Filterer
     |      __builtin__.object
     |  
     |  Methods defined here:
     |  
     |  createLock(self)
     |  
     |  emit(self, record)
     |  
     |  handle(self, record)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from Handler:
     |  
     |  __init__(self, level=0)
     |      Initializes the instance - basically setting the formatter to None
     |      and the filter list to empty.
     |  
     |  acquire(self)
     |      Acquire the I/O thread lock.
     |  
     |  close(self)
     |      Tidy up any resources used by the handler.
     |      
     |      This version removes the handler from an internal map of handlers,
     |      _handlers, which is used for handler lookup by name. Subclasses
     |      should ensure that this gets called from overridden close()
     |      methods.
     |  
     |  flush(self)
     |      Ensure all logging output has been flushed.
     |      
     |      This version does nothing and is intended to be implemented by
     |      subclasses.
     |  
     |  format(self, record)
     |      Format the specified record.
     |      
     |      If a formatter is set, use it. Otherwise, use the default formatter
     |      for the module.
     |  
     |  get_name(self)
     |  
     |  handleError(self, record)
     |      Handle errors which occur during an emit() call.
     |      
     |      This method should be called from handlers when an exception is
     |      encountered during an emit() call. If raiseExceptions is false,
     |      exceptions get silently ignored. This is what is mostly wanted
     |      for a logging system - most users will not care about errors in
     |      the logging system, they are more interested in application errors.
     |      You could, however, replace this with a custom handler if you wish.
     |      The record which was being processed is passed in to this method.
     |  
     |  release(self)
     |      Release the I/O thread lock.
     |  
     |  setFormatter(self, fmt)
     |      Set the formatter for this handler.
     |  
     |  setLevel(self, level)
     |      Set the logging level of this handler.
     |  
     |  set_name(self, name)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from Handler:
     |  
     |  name
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from Filterer:
     |  
     |  addFilter(self, filter)
     |      Add the specified filter to this handler.
     |  
     |  filter(self, record)
     |      Determine if a record is loggable by consulting all the filters.
     |      
     |      The default is to allow the record to be logged; any filter can veto
     |      this and the record is then dropped. Returns a zero value if a record
     |      is to be dropped, else non-zero.
     |  
     |  removeFilter(self, filter)
     |      Remove the specified filter from this handler.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from Filterer:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    class StreamHandler(Handler)
     |  A handler class which writes logging records, appropriately formatted,
     |  to a stream. Note that this class does not close the stream, as
     |  sys.stdout or sys.stderr may be used.
     |  
     |  Method resolution order:
     |      StreamHandler
     |      Handler
     |      Filterer
     |      __builtin__.object
     |  
     |  Methods defined here:
     |  
     |  __init__(self, stream=None)
     |      Initialize the handler.
     |      
     |      If stream is not specified, sys.stderr is used.
     |  
     |  emit(self, record)
     |      Emit a record.
     |      
     |      If a formatter is specified, it is used to format the record.
     |      The record is then written to the stream with a trailing newline.  If
     |      exception information is present, it is formatted using
     |      traceback.print_exception and appended to the stream.  If the stream
     |      has an 'encoding' attribute, it is used to determine how to do the
     |      output to the stream.
     |  
     |  flush(self)
     |      Flushes the stream.
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from Handler:
     |  
     |  acquire(self)
     |      Acquire the I/O thread lock.
     |  
     |  close(self)
     |      Tidy up any resources used by the handler.
     |      
     |      This version removes the handler from an internal map of handlers,
     |      _handlers, which is used for handler lookup by name. Subclasses
     |      should ensure that this gets called from overridden close()
     |      methods.
     |  
     |  createLock(self)
     |      Acquire a thread lock for serializing access to the underlying I/O.
     |  
     |  format(self, record)
     |      Format the specified record.
     |      
     |      If a formatter is set, use it. Otherwise, use the default formatter
     |      for the module.
     |  
     |  get_name(self)
     |  
     |  handle(self, record)
     |      Conditionally emit the specified logging record.
     |      
     |      Emission depends on filters which may have been added to the handler.
     |      Wrap the actual emission of the record with acquisition/release of
     |      the I/O thread lock. Returns whether the filter passed the record for
     |      emission.
     |  
     |  handleError(self, record)
     |      Handle errors which occur during an emit() call.
     |      
     |      This method should be called from handlers when an exception is
     |      encountered during an emit() call. If raiseExceptions is false,
     |      exceptions get silently ignored. This is what is mostly wanted
     |      for a logging system - most users will not care about errors in
     |      the logging system, they are more interested in application errors.
     |      You could, however, replace this with a custom handler if you wish.
     |      The record which was being processed is passed in to this method.
     |  
     |  release(self)
     |      Release the I/O thread lock.
     |  
     |  setFormatter(self, fmt)
     |      Set the formatter for this handler.
     |  
     |  setLevel(self, level)
     |      Set the logging level of this handler.
     |  
     |  set_name(self, name)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from Handler:
     |  
     |  name
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from Filterer:
     |  
     |  addFilter(self, filter)
     |      Add the specified filter to this handler.
     |  
     |  filter(self, record)
     |      Determine if a record is loggable by consulting all the filters.
     |      
     |      The default is to allow the record to be logged; any filter can veto
     |      this and the record is then dropped. Returns a zero value if a record
     |      is to be dropped, else non-zero.
     |  
     |  removeFilter(self, filter)
     |      Remove the specified filter from this handler.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from Filterer:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)

FUNCTIONS
    addLevelName(level, levelName)
        Associate 'levelName' with 'level'.
        
        This is used when converting levels to text during message formatting.
    
    basicConfig(**kwargs)
        Do basic configuration for the logging system.
        
        This function does nothing if the root logger already has handlers
        configured. It is a convenience method intended for use by simple scripts
        to do one-shot configuration of the logging package.
        
        The default behaviour is to create a StreamHandler which writes to
        sys.stderr, set a formatter using the BASIC_FORMAT format string, and
        add the handler to the root logger.
        
        A number of optional keyword arguments may be specified, which can alter
        the default behaviour.
        
        filename  Specifies that a FileHandler be created, using the specified
                  filename, rather than a StreamHandler.
        filemode  Specifies the mode to open the file, if filename is specified
                  (if filemode is unspecified, it defaults to 'a').
        format    Use the specified format string for the handler.
        datefmt   Use the specified date/time format.
        level     Set the root logger level to the specified level.
        stream    Use the specified stream to initialize the StreamHandler. Note
                  that this argument is incompatible with 'filename' - if both
                  are present, 'stream' is ignored.
        
        Note that you could specify a stream created using open(filename, mode)
        rather than passing the filename and mode in. However, it should be
        remembered that StreamHandler does not close its stream (since it may be
        using sys.stdout or sys.stderr), whereas FileHandler closes its stream
        when the handler is closed.
    
    captureWarnings(capture)
        If capture is true, redirect all warnings to the logging package.
        If capture is False, ensure that warnings are not redirected to logging
        but to their original destinations.
    
    critical(msg, *args, **kwargs)
        Log a message with severity 'CRITICAL' on the root logger.
    
    debug(msg, *args, **kwargs)
        Log a message with severity 'DEBUG' on the root logger.
    
    disable(level)
        Disable all logging calls of severity 'level' and below.
    
    error(msg, *args, **kwargs)
        Log a message with severity 'ERROR' on the root logger.
    
    exception(msg, *args, **kwargs)
        Log a message with severity 'ERROR' on the root logger,
        with exception information.
    
    fatal = critical(msg, *args, **kwargs)
        Log a message with severity 'CRITICAL' on the root logger.
    
    getLevelName(level)
        Return the textual representation of logging level 'level'.
        
        If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
        INFO, DEBUG) then you get the corresponding string. If you have
        associated levels with names using addLevelName then the name you have
        associated with 'level' is returned.
        
        If a numeric value corresponding to one of the defined levels is passed
        in, the corresponding string representation is returned.
        
        Otherwise, the string "Level %s" % level is returned.
    
    getLogger(name=None)
        Return a logger with the specified name, creating it if necessary.
        
        If no name is specified, return the root logger.
    
    getLoggerClass()
        Return the class to be used when instantiating a logger.
    
    info(msg, *args, **kwargs)
        Log a message with severity 'INFO' on the root logger.
    
    log(level, msg, *args, **kwargs)
        Log 'msg % args' with the integer severity 'level' on the root logger.
    
    makeLogRecord(dict)
        Make a LogRecord whose attributes are defined by the specified dictionary,
        This function is useful for converting a logging event received over
        a socket connection (which is sent as a dictionary) into a LogRecord
        instance.
    
    setLoggerClass(klass)
        Set the class to be used when instantiating a logger. The class should
        define __init__() such that only a name argument is required, and the
        __init__() should call Logger.__init__()
    
    warn = warning(msg, *args, **kwargs)
        Log a message with severity 'WARNING' on the root logger.
    
    warning(msg, *args, **kwargs)
        Log a message with severity 'WARNING' on the root logger.

DATA
    BASIC_FORMAT = '%(levelname)s:%(name)s:%(message)s'
    CRITICAL = 50
    DEBUG = 10
    ERROR = 40
    FATAL = 50
    INFO = 20
    NOTSET = 0
    WARN = 30
    WARNING = 30
    __all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', ...
    __author__ = 'Vinay Sajip <[email protected]>'
    __date__ = '07 February 2010'
    __status__ = 'production'
    __version__ = '0.5.1.2'

VERSION
    0.5.1.2

DATE
    07 February 2010

AUTHOR
    Vinay Sajip <[email protected]>



Process finished with exit code 0
复制代码

 

 见如下的代码,来看logging模块的应用,见代码:

复制代码
logging.basicConfig(filename='log.md',
                    format='%(asctime)s-%(name)s-%(levelname)s-%(module)s:%(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=10)
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')
复制代码

 

注释:filename后面跟的是存储日志内容的文件名称,format是日志的格式,datefmt是时间格式,level是等级,那么

扫描二维码关注公众号,回复: 1533229 查看本文章

level怎么来评估了,或者说是如何获取了,到logging的模块中,可以看到每个等级对应的数值,见源码:

复制代码
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

_levelNames = {
    CRITICAL : 'CRITICAL',
    ERROR : 'ERROR',
    WARNING : 'WARNING',
    INFO : 'INFO',
    DEBUG : 'DEBUG',
    NOTSET : 'NOTSET',
    'CRITICAL' : CRITICAL,
    'ERROR' : ERROR,
    'WARN' : WARNING,
    'WARNING' : WARNING,
    'INFO' : INFO,
    'DEBUG' : DEBUG,
    'NOTSET' : NOTSET,
}
复制代码

 

我们执行最先开始的代码,看log.md文件的内容是什么?见log.md文件的内容:

注释:可以看到,执行后,对应的内容纪录到了log.md的文件中,当然这里仅仅是测试的代码。

   见如下的代码,更加的简单,来看如何实现写log的过程,见代码:

复制代码
#!/usr/bin/env python 
#-*- coding:utf-8 -*-

import  logging

#定义文件
logFile=logging.FileHandler('logInfo.md','a')
#log格式
fmt=logging.Formatter(fmt='%(asctime)s-%(name)s-%(levelname)s-%(module)s:%(message)s')
logFile.setFormatter(fmt)

#定义日志
logger1=logging.Logger('logTest',level=logging.DEBUG)
logger1.addHandler(logFile)

#写日志
logger1.critical('info')
复制代码

 

执行如上的代码后,logInfo.md文件中会写入如下的内容,见log的内容:

下面修改下代码,实际的应用下,编写一个自动化的测试,把log写入到文件中,见代码:

复制代码
#!/usr/bin/env python 
#-*- coding:utf-8 -*-

import  logging
from selenium import  webdriver
import  unittest


def log(log_content):
    # 定义文件
    logFile = logging.FileHandler('logInfo.md', 'a')
    # log格式
    fmt = logging.Formatter(fmt='%(asctime)s-%(name)s-%(levelname)s-%(module)s:%(message)s')
    logFile.setFormatter(fmt)

    # 定义日志
    logger1 = logging.Logger('logTest', level=logging.DEBUG)
    logger1.addHandler(logFile)
    logger1.info(log_content)


class WebTest(unittest.TestCase):
    def setUp(self):
        log(u'UI自动化执行开始...')
        self.driver=webdriver.Firefox()
        self.driver.maximize_window()
        self.driver.implicitly_wait(30)
        self.driver.get('http://www.baidu.com')

    def test_baidu_title(self):
        log(u'验证百度首页的title')
        self.assertEqual(self.driver.title,u'百度一下,你就知道')
        log(u'断言验证成功')

    def tearDown(self):
        self.driver.quit()
        log(u'测试结束,关闭浏览器并且退出程序')

if __name__=='__main__':
    unittest.main(verbosity=2)
复制代码

 

见执行后的日志文件内容:

2017-08-29 23:02:50,539-logTest-INFO-logIndex:UI自动化执行开始...
2017-08-29 23:03:20,466-logTest-INFO-logIndex:验证百度首页的title
2017-08-29 23:03:20,493-logTest-INFO-logIndex:断言验证成功
2017-08-29 23:03:20,654-logTest-INFO-logIndex:测试结束,关闭浏览器并且退出程序

猜你喜欢

转载自blog.csdn.net/yyang3121/article/details/80533897
今日推荐