Python3 Log Module

Source: Internet
Author: User

Python3 Log Module

Python3 Log Module website description
High to low log levels in Python: CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET
The default log level is: WARNING, that is, when the log is displayed, logs below WARNING are not displayed
Example code:

#!/usr/bin/python3import logginglogging.info(‘this is the info message‘)logging.debug(‘this is the debug message‘)logging.warning(‘this is the warning message‘)logging.error(‘this is the error message‘)logging.critical(‘this is the critical message‘)

Output:
WARNING:root:this is WARNING message
ERROR:root:this is error message
CRITICAL:root:this is CRITICAL message

Log configuration

Logging.basicconfig () function to configure log level, log display format, log display messages, etc.
Relevant parameters and meanings are:

Parameters meaning
FileName Specify the file name of the storage log
Filemod Specifies the mode in which the log file opens, W or a
Level Specifies the log level, default logging. WARNING (must be capitalized here)
Format Specifies the format and content of the output, and the reference information for format is stated below
Datefmt Using the specified time format with asctime in the format parameter, you need to specify the format using DATEFMT

Example code:

#!/usr/bin/python3import logginglogging.basicConfig(filename=‘test.log‘,level=logging.DEBUG,format=‘%(asctime)s %(filename)s[line:%(lineno)d] %(message)s‘,datefmt=‘%Y-%m-%d %X‘)logging.info(‘ info logging‘)logging.debug(‘debug logging‘)logging.warning(‘warning logging‘)logging.error(‘error logging‘)logging.critical(‘critical logging‘)

Output:
WARNING:root:warning Logging
ERROR:root:error Logging
CRITICAL:root:critical Logging

Format output Formatting parameters
Parameters meaning
% (name) s Logger's name.
% (Levelno) s Print the value of the log level
% (LevelName) s Print Log level name
% (pathname) s Prints the full pathname of the module that called the log output function and may not have
% (filename) s Print the file name of the module that called the log output function
% (FuncName) s Function name of the print Call log output function
% (module) s The module name of the print Call log output function
% (Lineno) d The code line number where the statement that prints the call log output function is printed
% (created) f Current time, represented by the UNIX standard floating-point number representing the time
% (relativecreated) d The number of milliseconds since logger was created when the output log information is printed
% (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 Print thread ID, may not have
% (ThreadName) s Print thread name, may not have
% (process) d Print Process ID
% (message) s Print log information, which is the user output message
The concept of Logger,handler,formatter,filter
    • Logger provides an interface that the application can use directly;

    • Handler sends the log record (created by logger) to the appropriate destination output;

    • Filter provides a fine-grained device to determine which log record to output;

    • Formatter determines the final output format of the log record.
Logger

Each program obtains a logger before outputting the log. Logger usually corresponds to the program's module name, such as the chat tool's graphical interface module can get its logger:
Log=logging.getlogger ("Chat.gui")
And the core module can do this:
Log=logging.getlogger ("Chat.kernel")

Logger.setlevel (LEL): Specifies the lowest log level, and the level below LEL is ignored. Debug is the lowest built-in level, critical is the highest
Logger.addfilter (filt), Logger.removefilter (filt): Add or remove the specified filter
Logger.addhandler (HDLR), Logger.removehandler (HDLR): Add or remove the specified handler
Logger.debug (), Logger.info (), logger.warning (), Logger.error (), logger.critical (): Log levels you can set

Handler

The handler object is responsible for sending relevant information to the specified destination.
Python's log system can be used in a variety of handler.
Some handler can output information to the console.
Some logger can output information to a file.
There are also some handler that can send information to the Web.
If you feel that it is not enough, you can write your own handler.
Multiple handler can be added through the AddHandler () method
Handler.setlevel (LEL): Specifies the level of information being processed, and information below the LEL level is ignored
Handler.setformatter (): Choose a format for this Handler
Handler.addfilter (filt), Handler.removefilter (filt): Add or remove a filter object

Multiple handler can be attached to each logger.
Next, let's introduce some common handler:

1) logging. Streamhandler
Using this handler, you can output information to any file object, such as Sys.stdout or Sys.stderr. Its constructor is:
Streamhandler ([STRM])
Where the STRM parameter is a file object. Default is Sys.stderr

2) logging. Filehandler
Similar to Streamhandler, used to output log information to a file.
But Filehandler will open this file for you. Its constructor is:
Filehandler (Filename[,mode])
FileName is a file name and you must specify a file name.
Mode is how the file is opened. See the use of the Python built-in function open (). The default is ' a ', which is append.

3) Logging.handlers.RotatingFileHandler
This handler is similar to the filehandler above, but it can manage the file size.
When the file reaches a certain size, it automatically renames the current log file and then creates a new log file with the same name to continue the output.
For example, the log file is Chat.log. When the chat.log reaches the specified size, Rotatingfilehandler automatically renames the file to Chat.log.1.
However, if chat.log.1 already exists, it will first rename chat.log.1 to chat.log.2 ... Finally, re-create the Chat.log and continue to output the log information.
Its constructor is:
Rotatingfilehandler (filename[, mode[, maxbytes[, Backupcount]])
where filename and mode two parameters are the same as Filehandler.
The maxbytes is used to specify the maximum file size for the log file.
If MaxBytes is 0, it means that the log file can be infinitely large, and the renaming process described above does not occur.
The backupcount is used to specify the number of reserved backup files.
For example, if you specify 2, when the renaming process described above occurs, the original chat.log.2 is not renamed, but is deleted.

4) Logging.handlers.TimedRotatingFileHandler
This handler is similar to Rotatingfilehandler, however, it does not determine when to recreate the log file by judging the size of the file, but instead automatically creates a new log file at a certain time interval.
The process of renaming is similar to Rotatingfilehandler, but the new file is not an appended number but the current time.
Its constructor is:
Timedrotatingfilehandler (filename [, when [, interval [, Backupcount]])
where the filename parameter and the Backupcount parameter and the Rotatingfilehandler have the same meaning.
Interval is the time interval.
The When parameter is a string. A unit that represents a time interval, not case-sensitive. It has the following values:
s S
M min
H hours
D Day
W per week (Interval==0 on behalf of Monday)
Midnight every morning

Encapsulated log functions

Example code:

 #!/usr/bin/pythonimport loggingimport Osimport sysbase_dir = Os.path.dirname (Os.path.dirname (Os.path.abspath ( __file__))) Sys.path.append (Base_dir) "" "Project Use requirements: 1-Different log names 2-print at the same time in the console, there is also a file 3-record control Level" "" # logging.disable (logging. CRITICAL) # Disable output log def public_log (logger_name= ' Default-log ', Log_file=os.path.join (base_dir, ' log ', ' Dataoperate.log ') ), level=logging. DEBUG): Logger = Logging.getlogger (logger_name) Logger.setlevel (level) # Add Log rank # Create console console Handler ch = Logging. Streamhandler () # Sets the console output when the log level ch.setlevel (logging. WARNING) # Create file handler fh = logging. Filehandler (Filename=log_file, encoding= ' Utf-8 ') # Sets the log level to write to the file Fh.setlevel (logging. DEBUG) # Create Formatter formatter = logging. Formatter ('% (asctime) s% (filename) s [line:% (Lineno) d]% (name) s% (levelname) s% (message) s ') # add Formatter Ch.setforma Tter (Formatter) Fh.setformatter (formatter) # Add CH FH to logger logger.addhandler (CH) logger.addhandler (FH) r Eturn Logger 

Python3 Log 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.