The Python logging module is a new feature introduced in 2.3 to handle log management during program running.
Share some common classes and module-level functions of this module.
Module-level functions
Logging. getLogger ([name]): returns a logger object. If no name is specified, the root logger is returned.
Logging. debug (), logging.info (), logging. warning (), logging. error (), and logging. critical (): Set the Log Level of the root logger.
Logging. basicConfig (): use the default Formatter to create a StreamHandler for the log system, set the basic configuration, and add it to the root logger.
Example: logging_level_example.py
import loggingimport sysLEVELS = {'debug': logging.DEBUG,'info': logging.INFO,'warning': logging.WARNING,'error': logging.ERROR,'critical': logging.CRITICAL}if len(sys.argv) > 1:level_name = sys.argv[1]level = LEVELS.get(level_name, logging.NOTSET)logging.basicConfig(level=level)logging.debug('This is a debug message')logging.info('This is an info message')logging.warning('This is a warning message')logging.error('This is an error message')logging.critical('This is a critical error message')
Output:
$ python logging_level_example.py debugDEBUG:root:This is a debug messageINFO:root:This is an info messageWARNING:root:This is a warning messageERROR:root:This is an error messageCRITICAL:root:This is a critical error message$ python logging_level_example.py infoINFO:root:This is an info messageWARNING:root:This is a warning messageERROR:root:This is an error messageCRITICAL:root:This is a critical error message
Loggers
Logger. setLevel (lel): Specify the lowest log level. If it is lower than lel, it will be ignored. Debug is the lowest built-in level, and critical is the highest
Logger. addFilter (filt), Logger. removeFilter (filt): add or delete the specified filter www.jbxue.com
Logger. addHandler (hdlr) and Logger. removeHandler (hdlr): add or delete a specified handler.
Logger. debug (), Logger.info (), Logger. warning (), Logger. error (), Logger. critical (): the log level that can be set
Example: simple_logging_module.py
import logging# create loggerlogger = logging.getLogger("simple_example")logger.setLevel(logging.DEBUG)# create console handler and set level to debugch = logging.StreamHandler()ch.setLevel(logging.DEBUG)# create formatterformatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")# add formatter to chch.setFormatter(formatter)# add ch to loggerlogger.addHandler(ch)# "application" codelogger.debug("debug message")logger.info("info message")logger.warn("warn message")logger.error("error message")logger.critical("critical message")
Output:
$ Python simple_logging_module.py
15:10:26, 618-simple_example-DEBUG-debug message
15:10:26, 620-simple_example-INFO-info message
15:10:26, 695-simple_example-WARNING-warn message
15:10:26, 697-simple_example-ERROR-error message
15:10:26, 773-simple_example-CRITICAL-critical message
Handlers
The handler object is responsible for sending relevant information to the specified destination. You can add multiple handler using the addHandler () method.
Handler. setLevel (lel): Specifies the level of information to be processed. Information lower than the lel level will be ignored.
Handler. setFormatter (): select a format for the handler.
Handler. addFilter (filt), Handler. removeFilter (filt): Adds or deletes a filter object.
Formatters
The Formatter object sets the last rule, structure, and content of log information. The default time format is % Y-% m-% d % H: % M: % S, below are some common information about Formatter.
% (Name) s
Logger name
% (Levelno) s
Log Level in digital form
% (Levelname) s
Log Level in text format
% (Pathname) s
The complete path name of the module that calls the log output function.
% (Filename) s
File Name of the module that calls the log output function
% (Module) s
The name of the module that calls the log output function.
% (FuncName) s
Name of the function that calls the log output function
% (Lineno) d
The code line of the statement that calls the log output function
% (Created) f
Current Time, represented by floating points of time in UNIX standard
% (RelativeCreated) d
Number of milliseconds since Logger was created when log information is output
% (Asctime) s
The current time in string format. The default format is "16:49:45, 896 ". The comma is followed by a millisecond
% (Thread) d
Thread ID. Not possible
% (ThreadName) s
Thread name. Not possible
% (Process) d
Process ID. Not possible
% (Message) s
User Output Message
Complete example:
import logging# set up logging to file - see previous section for more detailslogging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',datefmt='%m-%d %H:%M',filename='/temp/myapp.log',filemode='w')# define a Handler which writes INFO messages or higher to the sys.stderrconsole = logging.StreamHandler()console.setLevel(logging.INFO)# set a format which is simpler for console useformatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')# tell the handler to use this formatconsole.setFormatter(formatter)# add the handler to the root loggerlogging.getLogger('').addHandler(console)# Now, we can log to the root logger, or any other logger. First the root...logging.info('Jackdaws love my big sphinx of quartz.')# Now, define a couple of other loggers which might represent areas in your# application:www.jbxue.comlogger1 = logging.getLogger('myapp.area1')logger2 = logging.getLogger('myapp.area2')logger1.debug('Quick zephyrs blow, vexing daft Jim.')logger1.info('How quickly daft jumping zebras vex.')logger2.warning('Jail zesty vixen who grabbed pay from quack.')logger2.error('The five boxing wizards jump quickly.')
Result displayed on the terminal after running
Root: INFO Jackdaws love my big sphinx of quartz.
Myapp. area1: INFO How quickly daft jumping zebras vex.
Myapp. area2: WARNING Jail zesty vixen who grabbed pay from quack.
Myapp. area2: ERROR The five boxing wizards jump quickly.
Results In the log file
10-22 root INFO Jackdaws love my big sphinx of quartz.
10-22 myapp. area1 DEBUG Quick zephyrs blow, vexing daft Jim.
10-22 myapp. area1 INFO How quickly daft jumping zebras vex.
10-22 myapp. area2 WARNING Jail zesty vixen who grabbed pay from quack.
10-22 myapp. area2 ERROR The five boxing wizards jump quickly.
It is found that the DEBUG information only appears in the file, because the setLevel in StreamHandler is INFO. We can see the difference between Logger. setLevel () and handler. setLevel ().
For more information, see http://docs.python.org/library/logging.html