Python's powerful log module __python

Source: Internet
Author: User
Tags rollback
Author: txw1958 | Source: Blog Park | 2011/10/21 19:41:55 | Read 43 times 1. Simply print the log to the screen

Import logging

Logging.debug (' This are debug message ')
Logging.info (' This is info ')
Logging.warning (' This are warning message ')

Print on screen:
WARNING:root:This is WARNING message

By default, logging prints the log to the screen with a log level of warning;
The log level size relationship is: CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET, and of course you can define the logging level yourself. 2. Through the Logging.basicconfig function to the log output format and way to do related configuration

Import logging

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= ' Myapp.log ',
Filemode= ' W ')

Logging.debug (' This are debug message ')
Logging.info (' This is info ')
Logging.warning (' This are warning message ')

The content in the./myapp.log file is:
Sun, May 2009 21:48:54 Demo2.py[line:11] The debug this are debug message
Sun, May 2009 21:48:54 Demo2.py[line:12] Info this is info
Sun, May 2009 21:48:54 Demo2.py[line:13] WARNING this are WARNING message

logging.basicconfig function Parameters:
FileName: Specify log file name
FileMode: With the same meaning as the file function, specify the open mode of the log file, ' W ' or ' a '
Format: Specifies the formatting and content of the output, and the format can output a lot of useful information, as shown in the previous example:
% (Levelno) S: Print log-level values
% (levelname) S: Print log level name
% (pathname) s: Prints the path of the current execution program, which is actually sys.argv[0]
% (filename) S: Print the current executing program name
% (funcName) s: Print the current function of the log
% (Lineno) d: Print the current line number of the log
% (asctime) s: Time to print log
% (thread) d: Print thread ID
% (threadname) s: Print thread name
% (process) d: printing process ID
% (message) s: Print log information
DATEFMT: Specify time format, with Time.strftime ()
Level: Set the logging levels, default to logging. WARNING
Stream: Specifies the output stream of the log, which specifies the output to the Sys.stderr,sys.stdout or file, the default output to Sys.stderr, and the stream is ignored 3 when the stream and filename are specified at the same time . Output logs to files and screens at the same time

Import logging

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= ' Myapp.log ',
Filemode= ' W ')

#################################################################################################
#定义一个StreamHandler, print the info level or higher log information to the standard error and add it to the current log processing object #
console = logging. Streamhandler ()
Console.setlevel (Logging.info)
Formatter = logging. Formatter ('% (name) -12s:% (levelname) -8s% (message) s ')
Console.setformatter (Formatter)
Logging.getlogger ("). AddHandler (console)
#################################################################################################

Logging.debug (' This are debug message ')
Logging.info (' This is info ')
Logging.warning (' This are warning message ')

Print on screen:
Root:info this are INFO message
Root:warning this are WARNING message

The content in the./myapp.log file is:
Sun, May 2009 21:48:54 Demo2.py[line:11] The debug this are debug message
Sun, May 2009 21:48:54 Demo2.py[line:12] Info this is info
Sun, May 2009 21:48:54 Demo2.py[line:13] WARNING this are WARNING message

log rollback of 4.logging

Import logging
From logging.handlers import Rotatingfilehandler

#################################################################################################
#定义一个RotatingFileHandler, backup up to 5 log files, maximum 10M per log file
Rthandler = Rotatingfilehandler (' Myapp.log ', maxbytes=10*1024*1024,backupcount=5)
Rthandler.setlevel (Logging.info)
Formatter = logging. Formatter ('% (name) -12s:% (levelname) -8s% (message) s ')
Rthandler.setformatter (Formatter)
Logging.getlogger ("). AddHandler (Rthandler)
################################################################################################

From the above example and this example, we can see that logging has a main object of log processing, and other processing methods are added through AddHandler.
Several handle ways of logging are as follows:

Logging. Streamhandler: Log output to stream, can be sys.stderr, sys.stdout, or file
Logging. Filehandler: Log output to File

Log rollback mode, when used in Rotatingfilehandler and Timedrotatingfilehandler
Logging.handlers.BaseRotatingHandler
Logging.handlers.RotatingFileHandler
Logging.handlers.TimedRotatingFileHandler

Logging.handlers.SocketHandler: Remote output log to TCP/IP sockets
Logging.handlers.DatagramHandler: Remote output log to UDP sockets
Logging.handlers.SMTPHandler: Remote output log to mail address
Logging.handlers.SysLogHandler: Log Output to Syslog
Logging.handlers.NTEventLogHandler: Remote output log to the Windows NT/2000/XP event log
Logging.handlers.MemoryHandler: Log output to memory in the formulation buffer
Logging.handlers.HTTPHandler: Remote output to HTTP server via ' get ' or ' POST '

Because Streamhandler and filehandler are common log processing methods, they are included directly in the logging module, while others are included in the Logging.handlers module.
Refer to the python2.5 manual for the use of the other processing methods mentioned above. 5. Configuring logs through the Logging.config module

#logger. conf

###############################################

[Loggers]
Keys=root,example01,example02

[Logger_root]
Level=debug
Handlers=hand01,hand02

[LOGGER_EXAMPLE01]
Handlers=hand01,hand02
Qualname=example01
Propagate=0

[LOGGER_EXAMPLE02]
Handlers=hand01,hand03
Qualname=example02
Propagate=0

###############################################

[Handlers]
Keys=hand01,hand02,hand03

[HANDLER_HAND01]
Class=streamhandler
Level=info
Formatter=form02
Args= (Sys.stderr,)

[HANDLER_HAND02]
Class=filehandler
Level=debug
Formatter=form01
args= (' Myapp.log ', ' a ')

[HANDLER_HAND03]
Class=handlers. Rotatingfilehandler
Level=info
Formatter=form02
args= (' Myapp.log ', ' a ', 10*1024*1024, 5)

###############################################

[Formatters]
Keys=form01,form02

[FORMATTER_FORM01]
format=% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s
Datefmt=%a,%d%b%Y%h:%m:%s

[FORMATTER_FORM02]
format=% (name) -12s:% (levelname) -8s% (message) s
datefmt=

Example 3:

Import logging
Import Logging.config

Logging.config.fileConfig ("logger.conf")
Logger = Logging.getlogger ("example01")

Logger.debug (' This are debug message ')
Logger.info (' This is info ')
Logger.warning (' This are warning message ')

Example 4:

Import logging
Import Logging.config

Logging.config.fileConfig ("logger.conf")
Logger = Logging.getlogger ("Example02")

Logger.debug (' This are debug message ')
Logger.info (' This is info ')
Logger.warning (' This are warning message ')

6.logging is thread-safe 7.logging redirect Strerr,strout
 Import logging Import sys class Streamtologger (object): "" "Fake file-like Stream object that redirects write
   s to a logger instance.
      "" "Def __init__ (self, Logger, log_level=logging.info): Self.logger = Logger Self.log_level = Log_level Self.linebuf = ' Def write (self, buf): For line in Buf.rstrip (). Splitlines (): Self.logger.log (self . Log_level, Line.rstrip ()) Logging.basicconfig (level=logging. DEBUG, format= '% (asctime) s:% (levelname) s:% (name) s:% (message) s ', filename= ' Out.log ', filemode= ' a ') Stdout_logge r = Logging.getlogger (' STDOUT ') SL = Streamtologger (Stdout_logger, logging.info) sys.stdout = SL Stderr_logger = logging . GetLogger (' STDERR ') SL = Streamtologger (Stderr_logger, logging. Error) Sys.stderr = SL print "Test to standard out" raise Exception (' Test to standard error ') 



We Define a custom File-like object called Streamtologger object which sends anything written to it to a logger instea D. We then create two instances of that object and replace Sys.stdout and Sys.stderr with our fake file-like 0>

The output logfile looks like this:

2011-08-14 14:46:20,573:info:stdout:test to standard out  
2011-08-14 14:46:20,573:error:stderr:traceback (most Recent call last):  
2011-08-14 14:46:20,574:error:stderr:  File "redirect.py", line,   
2011-08-14 14:46:20,574:error:stderr:raise Exception (' Test to Standard ERROR ')  
2011-08-14 14:46:20,574:error:stderr: Exception  
2011-08-14 14:46:20,574:error:stderr::  
2011-08-14 14:46:20,574:error:stderr:test to Standard Error  
2011-08-14 14:46:20,573:info:stdout:test to standard out
2011-08-14 14:46:20,573:error:stderr: Traceback (most recent):
2011-08-14 14:46:20,574:error:stderr:  File "redirect.py", 
Line 2011-08-14 14:46:20,574:error:stderr:raise Exception (' Test to Standard ERROR ')
2011-08-14 14:46:20,574:error: Stderr:exception
2011-08-14 14:46:20,574:error:stderr::
2011-08-14 14:46:20,574:error:stderr:test to Standard error

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.