The use of logging--common handlers in Python modules

Source: Internet
Author: User

First, Streamhandler

Stream handler--is included in one of the three handler in the logging module.

The ability to output log information to Sys.stdout, Sys.stderr, or class file objects (more specifically, objects that can support the write () and Flush () methods).

There is only one parameter:

class logging.StreamHandler(stream=None)

The log information is output to the specified stream and, if the stream is empty, is output to Sys.stderr by default.

Second, Filehandler

Logging module comes with one of the three handler. Inherit from Streamhandler. Output log information to a disk file.

Construction Parameters:

class logging.FileHandler(filename, mode=‘a‘, encoding=None, delay=False)

When the default mode is Append,delay to True, the file is not opened until the emit method is executed. By default, log files can grow infinitely.

Third, Nullhandler

Empty Operation Handler,logging module comes with one of the three handler.
No parameters.

Iv. Watchedfilehandler

Located in the Logging.handlers module. Used to monitor the status of a file, if the file is changed, close the current stream, reopen the file, and create a new stream. File changes due to the use of Newsyslog or logrotate. This handler is designed specifically for the Linux/unix system because the files that are being opened are not changed under the Windows system.
The parameters are the same as Filehandler:

class logging.handlers.WatchedFileHandler(filename, mode=‘a‘, encoding=None, delay=False)
Wu, Rotatingfilehandler

The Logging.handlers is located in the support loop log file.

class logging.handlers.RotatingFileHandler(filename, mode=‘a‘, maxBytes=0, backupCount=0, encoding=None, delay=0)

The parameters MaxBytes and Backupcount allow the log file to rollover when it reaches MaxBytes. When the file size reaches or exceeds maxbytes, a new log file is created. Either of the two parameters above is 0 o'clock and rollover will not occur. That is, there is no maxbytes limit on the file. Backupcount is the number of backups, that is, how many backups can be. The name is appended with the. 0-.N suffix after the base_name of the log, such as Example.log.1,example.log.1,..., example.log.10. The log file currently in use is Base_name.log.

Liu, Timedrotatingfilehandler

Timed loop Log handler, located in Logging.handlers, supports timed generation of new log files.

class logging.handlers.TimedRotatingFileHandler(filename, when=‘h‘, interval=1, backupCount=0, encoding=None, delay=False, utc=False)

When a parameter determines the type of time interval, the parameter interval determines how much time interval. such as when= ' D ', interval=2, refers to the time interval of two days, Backupcount decided to leave a few log files. Exceeding the quantity will discard the old log file.

The When parameter determines the type of time interval. The relationship between the two is as follows:

 ‘S‘         |  秒 ‘M‘         |  分 ‘H‘         |  时 ‘D‘         |  天 ‘W0‘-‘W6‘   |  周一至周日 ‘midnight‘  |  每天的凌晨

The UTC parameter represents the UTC time.

Vii. other Handler--sockethandler, Datagramhandler, Sysloghandler, Nteventhandler, Smtphandler, MemoryHandler, HTTPHandler

These handler are not commonly used, so please refer to the official documentation for more details handlers

Here's a simple example to illustrate the use of handler:

Example one-how to not use the configuration file (Streamhandler):
Import logging# set up logging to File-see previous sections for more Detailslogging.basicconfig (level=logging. DEBUG, format= '% (asctime) s% (name) -12s% (levelname) -8s% (message) s ', datefmt= '%m-%d %h:%m ', filename= '/temp/myapp.log ', filemode= ' W ') # define a Handler which writes INF O messages or higher to the sys.stderr# console = logging. Streamhandler () Console.setlevel (logging.info) # Set a format which is simpler for console use# formats formatter = logging. Formatter ('% (name) -12s:% (levelname) -8s% (message) s ') # tell the handler-use this format# Tell handler to use this format console.setformatter (formatter) # Add the handler to the root logger# as root Logger add Handlerlogging.getlogger ("). AddHandler (console) # Now, we can log to the root logger, or any other logger. First the root ... #默认使用的是root loggerlogging.info (' Jackdaws love my big sphinx of quartz. ') # Now, define a couple of all loggers which might represent areas in your# ApplicatIon:logger1 = Logging.getlogger (' myapp.area1 ') Logger2 = Logging.getlogger (' myapp.area2 ') logger1.debug (' Quick Zephyrs blow, vexing daft Jim. ') Logger1.info (' How quickly daft jumping zebras vex. ') Logger2.warning (' Jail Zesty vixen who grabbed pay from quack. ') Logger2.error (' The five boxing wizards jump quickly. ')

Output to console results:

root        : INFO     Jackdaws love my big sphinx of quartz.myapp.area1 : INFO     How quickly daft jumping zebras vex.myapp.area2 : WARNING  Jail zesty vixen who grabbed pay from quack.myapp.area2 : ERROR    The five boxing wizards jump quickly.
Example two-how to use the configuration file (Timedrotatingfilehandler):

Log.conf Log configuration file:

[loggers]keys=root,test.subtest,test[handlers]keys=consoleHandler,fileHandler[formatters]keys=simpleFormatter[logger_root]level=INFOhandlers=consoleHandler,fileHandler[logger_test]level=INFOhandlers=consoleHandler,fileHandlerqualname=tornadopropagate=0[logger_test.subtest]level=INFOhandlers=consoleHandler,fileHandlerqualname=rocket.raccoonpropagate=0[handler_consoleHandler] #输出到控制台的handlerclass=StreamHandlerlevel=DEBUGformatter=simpleFormatterargs=(sys.stdout,)[handler_fileHandler] #输出到日志文件的handlerclass=logging.handlers.TimedRotatingFileHandlerlevel=DEBUGformatter=simpleFormatterargs=(‘rocket_raccoon_log‘,‘midnight‘)[formatter_simpleFormatter]format=[%(asctime)s-%(name)s(%(levelname)s)%(filename)s:%(lineno)d]%(message)sdatefmt=logging.config.fileConfig(‘conf/log.conf‘)logger = getLogging()

To obtain the Logger method:

def getLogging():    return logging.getLogger("test.subtest")

Configure Logger and call:

logging.config.fileConfig(‘conf/log.conf‘)logger = getLogging()logger.info("this is an example!")

Both the console and the log file are output:

[2016-07-01 09:22:06,470-test.subtest(INFO)main.py:55]this is an example!

The handlers of the logging module in the Python module is outlined here.

The use of logging--common handlers in Python modules

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.