Print output-guided log file in Python

Source: Internet
Author: User

Print output-guided log file in Python

A. Use Sys.stdout to direct the print line to a log file of your definition, for example:

Import Sys# Make a copy of original stdout Routestdout_backup= Sys.stdout# define the log file that receives your log infolog_file= open ( "Message.log",  "W") # redirect Print Output to log filesys.stdout = log_fileprint  "now all print info would be written to Message.log" # any command line so you'll execute...log_file.close ()  # Restore the output to initial patternsys.stdout = stdout_backupprint " Now this would be presented on screen "  span>                 

B. Using logging module (normalized log output, recommended!!) )
Because the function of the logging module is more, the following will put some simple examples in the document, more detailed specific usage please poke here

Demand the best way to implement
Fault investigation or condition monitoring Logging.info () or Logging.debug () (the latter is commonly used for the purpose of targeted detection and diagnosis)
Specific Run event issue warning Logging.warning ()
Report error suppression not starting exception (common in error handlers for long-running server processes) Logging.error (), logging.exception () or logging.critical ()

The following are suggestions for the logging function that should be taken based on the severity of the event:

degree Usage Scenarios
DEBUG Getting a diagnosis problem is specific information
INFO Confirm that the program is working as expected
WARNING Gets unexpected information that occurs when the program is still running, which may throw an exception later (for example, insufficient disk space)
ERROR Gets the information that some of the program's features do not normally call this type of critical exception
CRITICAL Gets the most critical exception information that the program cannot continue to run

The default level is warning, which means that the logging function only tracks exceptions that are more severe than warning if not specifically configured.

Here are some examples of how to use the logging function to log information:

# this is a simple exampleimport logging# define the log file, file mode and logging levellogging.basicConfig(filename=‘example.log‘, filemode="w", level=logging.DEBUG)logging.debug(‘This message should go to the log file‘)logging.info(‘So should this‘)logging.warning(‘And this, too‘)

View the Example.log file to see the following information:

DEBUG:root:This message should go to the log fileINFO:root:So should thisWARNING:root:And this, too

Logging from multiple Files

# myapp.pyimport logging import mylibdef main (): Logging.basicconfig (Filename= ' Myapp.log ', level< Span class= "OP" >=logging.info) logging.info ( ' Started ') mylib.do_ Something () logging.info ( ' finished ') if __name__ ==  ' __main __ ': Main ()                
# mylib.pyimport loggingdef do_something(): logging.info(‘Doing something‘)

The output information is

INFO:root:StartedINFO:root:Doing somethingINFO:root:Finished

Change the format of the default output information

import logging# output format: output time - logging level - log messageslogging.basicConfig(format=‘%(asctime)s - %(levelname)s - %(message)s‘)logging.warning(‘This message will appear in python console.‘)

Print the following output directly in the Python console:

2016-8-2 2:59:11, 510 - WARNING - This message will appear in python console

Logging Advanced usage
The logging function can be configured arbitrarily by building logger or by reading the logging config file.

    • Construction of Logger method
Import logging# Create Loggerlogger= Logging.getlogger (' Simple_example ') logger.setlevel (logging. DEBUG)# Create console handler and set level to DEBUGCH= Logging. Streamhandler () Ch.setlevel (logging. DEBUG)# Create Formatterformatter= Logging. Formatter (‘% (Asctime) s-% (name) s-% (levelname) S- % (message) S) # Add formatter to Chch.setformatter (formatter) # add ch to loggerlogger.addhandler (CH) # ' Application ' Codelogger.debug ( ' debug message ') Logger.info (  ' info message ') Logger.warn ( ' warn message ') Logger.error ( ' error message ' ) logger.critical ( ' critical message ')      

The above program results are output to the Python console:

$ python simple_logging_module.py2005-13L1915:10:26,618-simple_example-debug-debugMessage2005-13L1915:10:26,620-simple_example-info-infoMessage2005-03-19 15:10:26, 695-simple_example-warning-warn message2005-03-19 15:10:26,697-simple_example-error-error Span class= "Hljs-keyword" >message2005-03- 19 15: 10: 26,773-simple_example-critical-critical message             
    • Read configuration file Method
import logging import logging.configlogging.config.fileConfig (< Span class= "hljs-string" > ' logging.conf ') # create Loggerlogger = logging.getlogger ( ' simpleexample ') < Span class= "hljs-comment" ># ' Application ' Codelogger.debug ( ' debug Message ') Logger.info ( ' info message ') Logger.warn (< Span class= "hljs-string" > ' warn message ') Logger.error ( ' error message ') Logger.critical ( ' critical message ')       

Where the logging.conf file format is: (In fact, the previous method of the various configuration parameters written to the logging.conf file)

[Loggers]keys=root,simpleexample[handlers]keys=consolehandler[formatters]keys=simpleformatter[logger_root]level=debughandlers=consolehandler[logger_simpleexample]level=debughandlers=consolehandlerqualname=simpleexamplepropagate=0[handler_consolehandler]Class=StreamhandlerLevel=DEBUGFormatter=SimpleformatterArgs=(Sys.stdout,) [Formatter_simpleformatter]Format=%(asctime)S- % (name) s - %  (levelname) s - Span class= "OP" >% (message) sdatefmt= m/%d /%y%I:%M:%S%p             

As before, the above file output results are:

$ python simple_logging_config.py2005-03-1915:38:55,977-simpleexample-debug-debugMessage2005-03-1915:38:55,979-simpleexample-info-infoMessage2005-03-19 15:38:56, 054-simpleexample-warning-warn message2005-03-19 15:38:56,055-simpleexample-error-error Span class= "Hljs-keyword" >message2005-03- 19 15: 38: 56,130-simpleexample-critical-critical message             

Reference: Stackoverflow:redirect prints to log file

Print output-guided log file in Python

Related Article

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.