Python's logging log module (ii) __python

Source: Internet
Author: User
Tags file info rollback

The night is lazy, directly moved bricks.

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 contents of the

./myapp.log file are:
Sun, 2009 21:48:54 demo2.py[line:11] Debug This is debug message
Su N, May 2009 21:48:54 Demo2.py[line:12] Info This is info
Sun, May 2009 21:48:54 Demo2.py[line:13] Warnin G This is 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

from:http://blog.csdn.net/yatere/article/details/6655445

Original address: Python module Logging HOWTO Official document First, Logging introduction

Logging is a way to track events as the software runs, and software developers are prompted to invoke some events by calling logging in code. Events can be described by describing the information, and of course the descriptive information can contain variables, because the descriptive information may be different for each trigger of the event. second, simple example

A simple example:

Import Logging
logging.warning (' Watch out! ')  # Information will print to console
logging.info (' I told ')  # will not print any information because the default level is higher than info

If you deposit the above code in a python file, then run:

WARNING:root:Watch out!

Info information does not appear in the console because the default level is warning higher than info. Log information contains log level and event description information, but don't care too much about root in the output, which will be introduced later. The actual output can give you any customization, and the formatting will be introduced later. iii. Storing the log information in a file

In the application we often need to store the log information in the file. Please recreate a new file and don't connect it to the Python file above.

Import Logging
logging.basicconfig (filename= ' Example.log ', level=logging. DEBUG) Logging.debug (' This message should go to the "
log file ')
logging.info (' so should this ')
Logging.warning (' And this, too ')

Runs him, then generates a log file Example.log, and opens it to see the specific log information:

 DEBUG:root:This message should went to the log file Info:root: So should this WARNING:root:And, too 

In this example, we saw how to set the log level, This is a threshold , to control the output of the log.
If you want to set the log level through the command line, you can do this:

--log=info 

And you can also get the arguments passed to –log, you can do this:

 getattr (Logging, Loglevel.upper ()) 

You can set the log level by using the Basicconfig () method-passing the levels parameter. You may want to check the legality of the level parameter value, as follows:

 # Assuming LogLevel is bound 
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.