Python Logging Module

Source: Internet
Author: User

Python's logging module provides a common logging system that can be easily used by third-party modules or applications. This module provides different log levels and can record logs in different ways, such as files, HTTP get/post,smtp,socket, etc., and can even implement specific logging methods on their own.

The logging module is the same as the log4j mechanism, but the specific implementation details are different. module provides logger,handler,filter,formatter.

Logger: Provides a log interface for use in code. There are two types of logger for the longest operation: configuring and sending log messages. The Logger object can be obtained by Logging.getlogger (name), and if you do not specify name, the root object is returned, and multiple times using the same name calls the GetLogger method to return the same logger object.

Handler: sends a log record to the appropriate destination (destination), such as a file, socket, etc. A Logger object can add multiple handler through the AddHandler method, and each handler can also define different log levels for the log rating filtering display.

Filter: Provides an elegant way to determine whether a log record is sent to handler.

Formatter: Specifies the specific format of the logging output. The formatter method requires two parameters: the format string of the message and the date string, both of which are optional.

Similar to log4j, calls to Logger,handler and log messages can have specific log levels (level), only at levels greater than logger and handler for log messages.

#!/usr/bin/env python#-*-coding=utf-8-*-ImportLogging#Create an instance of logging loggerLogger = Logging.getlogger ('Richard')#set the global log level to debuglogger.setlevel (logging.info)#create a handler of the screen and set the level to debugCH =logging. Streamhandler () Ch.setlevel (logging. DEBUG)#Create a log file of handler, and set the level to debugFH = logging. Filehandler ("Access.log") Fh.setlevel (logging. CRITICAL)#Format the logFormatter = logging. Formatter ("% (asctime) s-% (name) s-% (levelname) s-% (message) s")#Add formatter to CH and FHCh.setformatter (Formatter) fh.setformatter (formatter)#Add ch and fh to loggerlogger.addhandler (CH) logger.addhandler (FH)#' Application ' codeLogger.debug ("Debug Message") Logger.info ("Info Message") Logger.warn ("warn message") Logger.error ("error Message") logger.critical ("crititcal Message")
#输出结果
"
D:\Program Files (x86) \python34\python.exe" f:/python/alex/s12/blog/log.py 2016-03-22 06:13:09,764-richard-info- INFO message2016-03-22 06:13:09,764-richard-warning- warn Mes Sage2016-03-22 06:13:09,764-richard-error- ERROR message2016-03-22 06:13:09,764-richard-critical-< c7> crititcal messageaccess.log:2016-03-22 06:13:09,764-richard-critical-crititcal Message

The point to note here is Logger.setlevel (Logging.info) and ch.setlevel (logging. DEBUG) The difference:

By example:

#set the global log level to criticalLogger.setlevel (logging. CRITICAL)#create a handler of the screen and set the level to debugCH =logging. Streamhandler () Ch.setlevel (logging. DEBUG)#Create a log file of handler, and set the level to infoFH = logging. Filehandler ("Access.log") fh.setlevel (logging.info) output results:"D:\Program Files (x86) \python34\python.exe"f:/python/alex/s12/blog/log.py2016-03-22 06:20:10,712-richard-critical-crititcal Messageaccess.log:2016-03-22 06:20:10,712-richard-critical-crititcal Message

If the global log level is critical, local variables want to be set to info or debug will fail.

It can be concluded that the global level is higher than local, add the global set to debug, local can be set to warning, then logging will only output warng, ERROR, critical these three types.

Note: With regard to the configuration of formatter, the use of the form of% (<dict key>) s is the dictionary keyword substitution. The keywords provided include:

Attribute name Format Description
Args You shouldn ' t need to format this yourself. The tuple of arguments merged into msg to produce message , or a dict whose values is used for the merge (when the Re is only one argument, and it's a dictionary).
Asctime %(asctime)s Human-readable time when the is LogRecord created. By default this is the form ' 2003-07-08 16:49:45,896 ' (the numbers after the comma was millisecond portion of the time) .
Created %(created)f Time when the is LogRecord created (as returned by time.time() ).
Exc_info You shouldn ' t need to format this yourself. Exception tuple (à la sys.exc_info ) or, if no Exception has occurred, None.
FileName %(filename)s Filename portion of pathname .
FuncName %(funcName)s Name of function containing the logging call.
levelname % (LevelName) s Text logging level for the message ( ' DEBUG ' /span> ,   ' INFO ' ,   ' WARNING ' ,   ' ERROR ' , Code class= "docutils literal" > ' CRITICAL ' ).
Levelno %(levelno)s Numeric logging level for the message ( DEBUG ,,, INFO WARNING ERROR , CRITICAL ).
Lineno %(lineno)d Source line number where the logging is issued (if available).
Module %(module)s Module (name portion of filename ).
Msecs %(msecs)d Millisecond portion of the time when the was LogRecord created.
message % (message) s The logged message, computed As msg %  args . This is set Whenformatter.format ()  is invoked.
Msg You shouldn ' t need to format this yourself. The format string passed in the original logging call. Merged args message with to produce, or a arbitrary object (see Using arbitrary objects as messages).
Name %(name)s Name of the logger used to log the call.
Pathname %(pathname)s Full pathname of the source file where the logging is issued (if available).
Process %(process)d Process ID (if available).
ProcessName %(processName)s Process name (if available).
relativecreated %(relativeCreated)d Time in milliseconds when the LogRecord is created, relative to the time of the logging module was loaded.
Stack_info You shouldn ' t need to format this yourself. stack frame information (where available) from the bottom of the "the Stack in the" The current thread, "up" and including the Stac K Frame of the logging call which resulted in the creation of this record.
Thread %(thread)d Thread ID (if available).
ThreadName %(threadName)s Thread name (if available).

Logging website Address:

Https://docs.python.org/3.5/library/logging.html

This article transfers from: http://www.cnblogs.com/Richardzhu/p/5303887.html

Python Logging Module

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.