Python Log Print Module

Source: Internet
Author: User

1 Logging Module Introduction

Logging module is a python built-in standard module, mainly used for output log, you can set the level of output logs, log save path, log file rollback, etc., compared to print, has the following advantages:

    1. You can only output important information in release version by setting different log levels, without having to display a lot of debugging information;
    2. Print prints all the information to the standard output, which seriously affects the developer viewing other data from the standard output, and logging can be used by the developer to decide where to export the information and how to output it;

2 Logging module uses 2.1 basic use

Configure the logging basic settings, and then output the logs in the console,

1 ImportLogging2Logging.basicconfig (level = Logging.info,format ='% (asctime) s-% (name) s-% (levelname) s-% (message) s')3Logger = Logging.getlogger (__name__)4 5Logger.info ("Start Print Log")6Logger.debug ("Do something")7Logger.warning ("Something maybe fail.")8Logger.info ("Finish")

Many message levels can be selected in logging, such as debug, info, warning, error, and critical. By giving logger or handler different levels, developers can output only error messages to a particular record file, or only debug information when debugging.

Parameters of the Logging.basicconfig function:
FileName: Specifies the log file name;
FileMode: The same as the file function, specify the open mode of the log file, ' W ' or ' a ';
Format: Specifies the formats and contents of the output, format can output a lot of useful information,
Parameters: function

% (Levelno) S: Print the value of the log level
% (levelname) s: Print the name of the log level
% (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
DATEFMT: Specify time format, same as Time.strftime ();
Level: Sets the log levels by default to logging. warnning;
Stream: Specifies the output stream that will log, can specify output to Sys.stderr,sys.stdout or file, default output to Sys.stderr, stream is ignored when stream and filename are specified simultaneously;

2.2 Writing a log to a file

2.2.1 Writing a log to a file

Set logging, create a filehandler, set the format of the output message, add it to the logger, and then write the log to the specified file

1 ImportLogging2Logger = Logging.getlogger (__name__)3Logger.setlevel (level =logging.info)4Handler = logging. Filehandler ("Log.txt")5 handler.setlevel (logging.info)6Formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s')7 Handler.setformatter (Formatter)8 Logger.addhandler (handler)9 TenLogger.info ("Start Print Log") OneLogger.debug ("Do something") ALogger.warning ("Something maybe fail.") -Logger.info ("Finish")

Here is a log print assistant for the package:

1 Importlogging.handlers2 3 """4 % (Levelno) S: Print the value of the log level5 % (levelname) S: Print log level name6 % (pathname) s: Prints the path of the currently executing program, which is actually sys.argv[0]7 % (filename) s: Prints the current name of the executing program8 % (funcName) s: Print the current function of the log9 % (Lineno) d: Print the current line number of the logTen % (asctime) s: Time to print logs One % (thread) d: Print thread ID A % (threadname) s: Print thread name - % (process) d: Print process ID - % (message) s: Print log information the """ -  - classlogassistant: -Logger =None +     #The log is divided into 5 levels, from low to High, respectively: DEBUG INFO WARNING ERROR CRITICAL. These 5 levels, also correspond to 5 kinds of methods to hit the log: Debug, info, warning, error, critical. The default is warning, -  +levels = {"D": Logging. DEBUG, A               "I": Logging.info, at               "W": Logging. WARNING, -               "e": Logging. ERROR, -               "C": Logging. CRITICAL} -  -Log_level ="D" -Log_file ="Log.txt" inLog_max_byte = 10 * 1024 * 1024; -Log_backup_count = 5 to  + @staticmethod -     defGetLogger (): the         ifLogassistant.logger is  notNone: *             returnLogassistant.logger $ Panax NotoginsengLogassistant.logger = logging. Logger ("logassistant") -Log_handler = Logging.handlers.RotatingFileHandler (filename=Logassistant.log_file, themaxbytes=Logassistant.log_max_byte, +Backupcount=logassistant.log_backup_count) ALOG_FMT = logging. Formatter ("[% (asctime) s] [% (LevelName) s][func:% (funcName) s][thread:% (thread) d]:% (message) s") the Log_handler.setformatter (LOG_FMT) + LogAssistant.logger.addHandler (Log_handler) - LogAssistant.logger.setLevel (LogAssistant.levels.get (logassistant.log_level)) $         returnLogassistant.logger $  - defoutput_test (): -Logger =Logassistant.getlogger () theLogger.debug ("This is a debug msg!") - Wuyi if __name__=="__main__": theOutput_test ()

Python Log Print 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.