Use logging module in Python to print log log details _python

Source: Internet
Author: User
Tags log log

Learn a new technique or language, we must first learn how to adapt to this new technology, which in the adaptation process, we have to learn how to debug the program and play the corresponding log information, is called "as long as the log is good, no bugs can not solve", in our well-known information technology, The Log4xxx series, as well as the Android.util.Log packages for Android apps, are all for developers to get a better log information service. In the language of Python, we can also play log according to our own program.

Log information is different from the use of piling method to print a certain tag information, log can be based on the needs of the program to separate log levels, such as info, debug, warn and so on level of information, as long as real-time control log level switch can provide developers with better log information, Like log4xx, Logger,handler and log message calls can have specific log levels (levels) that are displayed only if the level of the log message is greater than the set level of logger and handler. Now I'll talk about some of the logging modules I use in Python.

Logging Module Introduction

Python's logging module provides a common logging system, and skilled use of logging modules makes it easy for developers to develop third-party modules or their own Python applications. The same module provides different logging levels, and can record logs in different ways, such as files, HTTP, Get/post,smtp,socket, and so on, and can even implement specific logging methods on its own. I'll focus on how to log logs using the file format below.

The logging module includes the four basic concepts of logger,handler,filter,formatter.

Logger: provides log interface for use in code. There are two types of logger operations: Configuring and sending log messages. The Logger object can be obtained by Logging.getlogger (name), and the root object is returned if name is not specified, and the same logger object is returned multiple times using the same name call GetLogger method.
handler: sends the log record to the appropriate destination (destination), such as file, socket, etc. A Logger object can add 0 to multiple handler through the AddHandler method, and each handler can define different log levels to achieve a log-rating filter 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 construction method requires two parameters: the format string of the message and the date string, both of which are optional.

Basic methods of Use

Some small programs we do not need to construct too complex log system, you can directly use the logging module Basicconfig function can be, the code is as follows:

Copy Code code as follows:

'''
Created on 2012-8-12

@author: walfred
@module: Loggingmodule. Basiclogger
'''
Import logging

Log_file = "./basic_logger.log"

Logging.basicconfig (filename = log_file, level = logging. DEBUG)

Logging.debug ("This is a debugmsg!")
Logging.info ("This is a infomsg!")
Logging.warn ("This is a warn msg!")
Logging.error ("This is a error msg!")
Logging.critical ("This is a critical msg!")

When we run the program we will find the Basic_logger.log file in the current directory of the file, and view the Basic_logger.log content as follows:

Copy Code code as follows:

INFO:root:this is a info msg!
DEBUG:root:this is a debug msg!
WARNING:root:this is a warn msg!
ERROR:root:this is a error msg!
CRITICAL:root:this is a CRITICAL msg!

What you need to explain is that I set the level to debug level, so the log log only shows log information that is above and above the levels. Information levels are: NotSet, debug, info, warn, error, critical. If you use this configuration in multiple modules, you can simply configure it in the main module, and the other modules will have the same effect.

More advanced version

The basic use of the above is relatively simple, did not show the logging module, suitable for small programs, now I introduce a more advanced version of the code, we need to set the logger, handler, formatter configuration.

Copy Code code as follows:

'''
Created on 2012-8-12

@author: walfred
@module: Loggingmodule. Nomallogger
'''
Import logging

Log_file = "./nomal_logger.log"
Log_level = logging. DEBUG

Logger = Logging.getlogger ("Loggingmodule"). Nomallogger ")
Handler = logging. Filehandler (Log_file)
Formatter = logging. Formatter ("[% (LevelName) s][% (funcName) s][% (asctime) s]% (message) S")

Handler.setformatter (Formatter)
Logger.addhandler (Handler)
Logger.setlevel (Log_level)

#test
Logger.debug ("This is a debug msg!")
Logger.info ("This is a info msg!")
Logger.warn ("This is a warn msg!")
Logger.error ("This is a error msg!")
Logger.critical ("This is a critical msg!")

At this point we looked at the Nomal_logger.log log file for the current directory, as follows:

Copy Code code as follows:

[DEBUG] [][2012-08-12 17:43:59,295]this is a debug msg!
[INFO] [][2012-08-12 17:43:59,295]this is a info msg!
[WARNING] [][2012-08-12 17:43:59,295]this is a warn msg!
[ERROR] [][2012-08-12 17:43:59,295]this is a error msg!
[CRITICAL] [][2012-08-12 17:43:59,295]this is a critical msg!

This is not difficult to understand, compared to the logging module described earlier, the final version below will be more complete.

Perfect version

This final version I use singleton design pattern to write a logger class, the code is as follows:

Copy Code code as follows:

'''
Created on 2012-8-12

@author: walfred
@module: Loggingmodule. Finallogger
'''

Import Logging.handlers

Class Finallogger:

Logger = None

levels = {"n": Logging. NOTSET,
"D": Logging. DEBUG,
"I": Logging.info,
"W": Logging. WARN,
"E": Logging. ERROR,
"C": Logging. CRITICAL}

Log_level = "D"
Log_file = "Final_logger.log"
Log_max_byte = 10 * 1024 * 1024;
Log_backup_count = 5

@staticmethod
Def GetLogger ():
If Finallogger.logger is not None:
Return Finallogger.logger

Finallogger.logger = logging. Logger ("Oggingmodule.") Finallogger ")
Log_handler = logging.handlers.RotatingFileHandler (filename = finallogger.log_file,\
MaxBytes = finallogger.log_max_byte,\
Backupcount = Finallogger.log_backup_count)
LOG_FMT = logging. Formatter ("[% (LevelName) s][% (funcName) s][% (asctime) s]% (message) S")
Log_handler.setformatter (LOG_FMT)
FinalLogger.logger.addHandler (Log_handler)
FinalLogger.logger.setLevel (FinalLogger.levels.get (Finallogger.log_level))
Return Finallogger.logger

if __name__ = = "__main__":
Logger = Finallogger.getlogger ()
Logger.debug ("This is a debug msg!")
Logger.info ("This is a info msg!")
Logger.warn ("This is a warn msg!")
Logger.error ("This is a error msg!")
Logger.critical ("This is a critical msg!")

The Final_logger.log content under the current directory is as follows:

Copy Code code as follows:

[DEBUG] [][2012-08-12 18:12:23,029]this is a debug msg!
[INFO] [][2012-08-12 18:12:23,029]this is a info msg!
[WARNING] [][2012-08-12 18:12:23,029]this is a warn msg!
[ERROR] [][2012-08-12 18:12:23,029]this is a error msg!
[CRITICAL] [][2012-08-12 18:12:23,029]this is a critical msg!

This final version, also I have been using, readers can add some other handler, such as Streamhandler and so on to get more log information, of course, you can also log information through the configuration file to complete.

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.