Python Log Module logging and python log logging

Source: Internet
Author: User

Python Log Module logging and python log logging
Python logging module logging1. Basic usage

Python provides a standard log interface, that is, the logging module. The log levels include DEBUG, INFO, WARNING, ERROR, and CRITICAL. The corresponding functions are debug (), info (), warning (), and error (), critical ().

>>> import logging >>> logging.debug("ni hao")>>> logging.info("ni hao2")>>> logging.warning("ni hao")WARNING:root:ni hao>>> logging.error("ni hao")ERROR:root:ni hao>>> logging.critical("ni hao")CRITICAL:root:ni hao>>> 

It can be found that the debug () and info () methods do not display any information, because the default log level is WARNING, so logs below this level are not recorded.

You can use the function basicCinfig to modify the log level.

>>> import logging>>> logging.basicConfig(level=logging.INFO)>>> logging.info("nihao")INFO:root:nihao>>> logging.debug("dfasl")>>> logging.basicConfig(level=logging.DEBUG)>>> logging.info(4)INFO:root:4>>>

The basicConfig () function can also define more content, as shown in figure

logging.basicConfig(format=log_format,datefmt='%Y-%m-%d %H:%M:%S %p',level=logging.DEBUG) 

Example

import logginglog_format = '%(filename)s %(funcName)s %(asctime)s %(message)s'log_filename = "logging_test.log"logging.basicConfig(filename=log_filename, format=log_format, datefmt='%Y-%m-%d %H:%M:%S:%S %p', filemode='w', level=logging.INFO)logging.warning("warning###########")logging.warning("error@@@@@@@@@@@@@@")logging.error("error~~~~~~~~~~~~~~~~")

Result (output file "logging_test.log)

del.py <module> 2015-04-30 16:29:02:02 PM warningdel.py <module> 2015-04-30 16:29:02:02 PM errordel.py <module> 2015-04-30 16:29:02:02 PM error

 

Parameters of the logging. basicConfig Function

Filename: Specify the log file name filemode: The same as the file function. Specify the log file opening mode, 'w' or 'A' format: Specify the output format and content, format can output a lot of useful information, as shown in the preceding example: % (levelno) s: print the log level value % (levelname) s: print the Log Level name % (pathname) s: print the path of the current execution program, which is actually sys. argv [0] % (filename) s: print the current execution program name % (funcName) s: print the current function of the log % (lineno) d: current row number of the print log % (asctime) s: log printing time % (thread) d: Print thread ID % (threadName) s: Print thread name % (process) d: print process ID % (message) s: Print log information datefmt: specifies the time format, the same as time. strftime () level: Set the log level. The default value is logging. WARNINGstream: Specifies the output stream of logs. You can specify the output stream to sys. stderr, sys. stdout or file, which is output to sys by default. stderr. When stream and filename are both specified, stream is ignored.

Note: The log is set to use the basicConfig () method. The default log writing method is 'A', that is, "APPEND". to overwrite the file, use filemode = 'W '.

The logging module is very powerful and can customize more complex log forms through more free interfaces. The following three objects are required: logger, formatter, and handler. The following describes logger

2. logger

The logger object directly provides the log interface.

The handler object can be used to write the log Content to different places.

For example, output logs to both files and screens.

# Coding: utf-8import logginglogger = logging. getLogger () logger. setLevel (logging. DEBUG) formatter = logging. formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') fh = logging. fileHandler ("test. log ") ch = logging. streamHandler () fh. setFormatter (formatter) ch. setFormatter (formatter) logger. addHandler (fh) # You can set addHandler to add content (fh, ch, fh + ch) to set the output location logger. addHandler (ch) logger. error ("error $") logger. debug ("aaaaa **********")
3. Module
#! /usr/bin/env python# --*-- coding:utf-8 --*--import osimport loggingimport logging.handlers#LOGGER = logging.getLogger(__name__)def init_log(LOGGER, log_file_path):    LOGGER.setLevel(logging.INFO)    ch = logging.StreamHandler()    ch.setLevel(logging.INFO)    formatter = logging.Formatter("%(asctime)s %(levelname)s %(filename)s(%(lineno)d) %(message)s ", "%Y-%m-%d %H:%M:%S")    ch.setFormatter(formatter)    LOGGER.addHandler(ch)    log_dir = os.path.dirname(log_file_path)    if not os.path.isdir(log_dir):        os.makedirs(log_dir)    fh = logging.handlers.RotatingFileHandler(log_file_path, maxBytes=10*1024*1024, backupCount=9)    fh.setLevel(logging.INFO)    fh.setFormatter(formatter)    LOGGER.addHandler(fh)if __name__=="__main__":    print "Unsupported in main module..."

Note: Logging. handlers. RotatingFileHandler
This Handler can manage the file size. When the file size reaches a certain value, it will automatically rename the current log file, and then create a new log file with the same name to continue output. For example, the log file is chat. log. When chat. log reaches the specified size, RotatingFileHandler automatically changes the file to chat. log.1. However, if chat. log.1 already exists, it will first rename chat. log.1 to chat. log.2. At last, re-create chat. log and continue to output log information. [This ensures the latest log in chat. log] its constructor is:
RotatingFileHandler (filename [, mode [, maxBytes [, backupCount])
The filename and mode parameters are the same as those of FileHandler.
MaxBytes is used to specify the maximum file size of a log file. If maxBytes is 0, it means that the log file can be infinitely large, and the renaming process described above will not happen.
BackupCount is used to specify the number of backup files to be retained. For example, if 2 is specified, the original chat. log.2 will not be renamed but will be deleted when the renaming process described above occurs.

 

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.