Python's logging Module 1

Source: Internet
Author: User

4. Log Format description

In the Logging.basicconfig function, you can specify the output format of the log, which can output a lot of useful information, as shown in the example above:

% (Levelno) S: Print the value of the log level
% (levelname) S: Print log level name
% (pathname) s: Prints the path of the currently executing program, which is actually sys.argv[0]
% (filename) s: Prints the current name of the executing program
% (funcName) s: Print the current function of the log
% (Lineno) d: Print the current line number of the log
% (asctime) s: Time to print logs
% (thread) d: Print thread ID
% (threadname) s: Print thread name
% (process) d: Print process ID
% (message) s: Print log information

The usual format I gave at work has been seen in the front. It is:

format= '% (asctime) s-% (filename) s[line:% (Lineno) d]-% (levelname) s:% (message) s '

This format can output the print time of the log, which module is output, what the log level of the output is, and the log content entered.

5. Advanced Step

Next you'll learn some of the log components and some advanced sections. The log components are: Loggers, handlers,filters,formatters.

The Logger object plays a triple role. First, it exposes several methods to apply so that the application can write log at run time. Second, the Logger object determines how the log information is handled (the default filtering function), depending on the severity of the log information or on the filter object. Finally, Logger is also responsible for transmitting the log information to the relevant loghandlers.

The handler object is responsible for assigning the appropriate log information (based on the severity of the log information) to the destination specified by handler. The Logger object can add 0 or more handler objects to itself by using the AddHandler () method. A common scenario is that an application might want to send all the log information to a log file, All log messages above the error level are sent to stdout, and all critical log messages are sent via email. This scenario requires three different handler handles, each handler responsible for sending a specific log message to a specific location.

Filter: Fine-grained, select which log output

Format: Setting display format

1, Logging.basicconfig ([**kwargs]):

Does Basic configuration for the logging system by creating a streamhandler with a defaultformatter and adding it to the R Oot logger. The Functionsdebug (), info (), warning (), error () andcritical () would callbasicconfig () automatically if no handlers are defined for the root logger.

This function does nothing if the root logger already have handlers configured for it.

Configure basic information for the log module. Kwargs supports several keyword parameters:
filename : The path where the log file is saved. If some parameters are configured, a filehandler is automatically created as a Handler;
FileMode : The open mode of the log file. The default value is ' a ', which means that the log message is added to the log file as an append. If set to ' W ', a new log file will be created each time the program starts;
Format: Set the log output formats;
datefmt : Define the date format;
levels: Sets the level of the log. Log messages below this level will be ignored;
Stream : sets the specific stream used to initialize the Streamhandler;

The demo is as follows:

Import logging
Import OS
FILE=OS.GETCWD ()
Logging.basicconfig (level=logging. DEBUG,
format= '% (asctime) s:% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ',
Datefmt= '%a,%d%b%Y%h:%m:%s ',
filename = Os.path.join (FILE, ' Log.txt '),
Filemode= ' W ')
Logging.info (' msg ')
Logging.debug (' MSG2 ')

2. Logging.getlogger ([name])

Creates a logger object. The work of logging is mainly done by the logger object. Provide the name of the logger when calling GetLogger (note: The same name is used more than once to invoke GetLogger, which returns a reference to the same object.) ), logger instances have hierarchical relationships, which are represented by logger names, such as:

p = Logging.getlogger ("root")

C1 = Logging.getlogger ("Root.c1")

C2 = Logging.getlogger ("Root.c2")

In the example, p is the parent logger, and C1,C2 is the child logger of P respectively. C1, C2 will inherit the settings of P. If the name parameter is omitted, GetLogger returns the root logger in the log object hierarchy.

Import logging
"' Name '
Log2=logging.getlogger (' Beginman ') #生成一个日志对象
Print log2 #<logging. Logger Object at 0x00000000026d1710>
"Nameless"
Log3 = Logging.getlogger ()
Print Log3 #<logging. Rootlogger object at 0x0000000002721630> returns Rootlogger if no name is specified
"The best way"
Log = Logging.getlogger (__name__) #__name__ is the module's name in the Python package namespace.
Print Log #<logging. Logger object at 0x0000000001cd5518> Logger
Print __name__ #__main__

Third, Logger object

by Logging.getlogger (NAM) to get the Logger object,

Class logging. Logger

The following properties and methods are available:

1, Logger.propagate

Print Log.propagate #1

Specific reference: http://docs.python.org/2.7/library/logging.html

2, Logger.setlevel (LVL)

Sets the level of the log. Log messages that are below this level are ignored.

Import logging
Import OS
Logging.basicconfig (format= "% (levelname) s,% (message) S", Filename=os.path.join (OS.GETCWD (), ' Log.txt '), level= Logging. DEBUG)
Log = Logging.getlogger (' root.set ') #Logger对象
Print Log.propagate #1
Log.info (' msg ') #不会被记录
Log.debug (' msg ') #不会被记录
Log.warning (' msg ')
Log.error (' msg ')

3. Logger.debug (msg [, *args [, **kwargs]])

Log information at the debug level is logged. The parameter msg is the format of the information, and the args and Kwargs are format parameters respectively.

Import logging
Logging.basicconfig (filename = Os.path.join (OS.GETCWD (), ' Log.txt '), level = logging. DEBUG)
Log = Logging.getlogger (' root ')
Log.debug ('%s,%s,%s ', * (' Error ', ' Debug ', ' info ')
Log.debug ('% (module) s,% (info) s ', {' module ': ' Log ', ' Info ': ' ERROR '})

4. Ibid.

5.1.1 Logger.info (msg[, *args[, **kwargs]) 5.1.2 logger.warnning (msg[, *args[, **kwargs]) 5.1.3 LOGGER.E Rror (msg[, *args[, **kwargs]) 5.1.4 logger.critical (msg[, *args[, **kwargs])

5, Logger.log (LVL, msg[, *args[, **kwargs])

Logging, parameter LVL user sets the level of log information. Parameter msg, *args, **kwargs the same meaning as logger.debug.

Log.log (logging. Error, '% (module) s% (info) s ', {' module ': ' Log log ', ' Info ': ' ERROR '}) #ERROR, log log error
Log.log (logging. Error, ' Go again:%s,%s ', * (' Log log ', ' Error ') #ERROR, repeat: Log log, error

6, Logger.exception (msg[, *args])

Log messages are logged at the error level, and exception tracking information is automatically added to the log messages. Logger.exception is used in exception handling blocks, such as:

Import logging
Import OS
Logging.basicconfig (format= "% (levelname) s,% (message) S", Filename=os.path.join (OS.GETCWD (), ' Log.txt '), level= Logging. DEBUG)
Log = Logging.getlogger (' root ') #Logger对象
Try
Raise Exception,u ' Error exception '
Except
Open the file, which appears as follows:
"' Error,exception
Traceback (most recent):
File "E:\project\py\src\log3.py", line A, in <module>
Raise Exception,u ' Error exception '
Exception: Error exception
‘‘‘

7,logger.addfilter(filt)

Specify filter

8,logger.removefilter(filt)

Removes the specified filter

9.Logger.filter(record)

.... The rest of the following describes

Python's logging Module 1

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.