Python module: Logging

Source: Internet
Author: User
Many programs have logging requirements, and the log contains information that has normal program access logs, there may be errors, warnings and other information output, Python's logging module provides a standard log interface, you can store various formats of the log, logging log can be divided into Debug, info, warning, error, critical 5 levels, let's take a look at how to use

Module Initial Knowledge:

#logging初识 Import Logging logging.warning ("User [James] attempted wrong password more than 3 times") logging.critical ("Ser Ver is off ") # WARNING:root:user [James] attempted wrong password more than 3 times# CRITICAL:root:server are down

The above code is the simplest way, the content in parentheses is the printed information, logging. After the method for the log level, see below for more information on the logging five levels

If you want to write the log into a file, it's also simple:

#日志打印到文件中 Import  Logging Logging.basicconfig (filename= "Example.log", Level=logging.info,                    format= "% ( Asctime) s% (message) s ", datefmt="%m/%d/%y%h:%m:%s [%A] ")                                                                # H 24-hour format  I 12 hour format  a week several complete  A-week few abbreviation  p am/pm< C7/>logging.debug ("This message should go to the log file") Logging.info (' so should this ') logging.warning ("And this, too")

Logging.basicconfig defines the input file path, enter the level of log information, input format, format can be customized; After executing the code, the Example.log file generates the following information:

10/31/2016 17:16:17 [Monday] so should this10/31/2016 17:16:17 [Monday] and this, too

One of the level=loggin in the following sentence. Info means that the logging level is set to info, that is, only logs that are higher than the log is info or the info level will be recorded in the file, in this case, the first log is not recorded, if you want to record the debug log, Then change the log level to debug.

If you want to print log on the screen and in the file log at the same time, you need to know a little bit of complexity:

The logging library takes a modular approach and offers several categories of components:loggers, handlers, filters, and Formatters.

Loggers expose the interface that application code directly uses.

Handlers send the log records (created by loggers) to the appropriate destination.

Filters provide a finer grained facility for determining which log records to output.

Formatters specify the layout of log records in the final output.

#!/usr/bin/env python#-*-coding:utf-8-*-#-author-lian import  Logging #创建loggerlogger = Logging.getlogger ("Test_ Log ")  #创建logger对象   parenthesis Content logger.setlevel (logging.info)       #全局日志级别  ch = logging. Streamhandler ()        #日志打印到屏幕上ch. SetLevel (logging. DEBUG)          #指定ch日志打印级别 fh = logging. Filehandler ("Access.log")      #日志存进文件fh. SetLevel (logging. WARNING)            #指定fh日志输入级别 formatter = logging. Formatter ("% (asctime) s-% (name) s-% (levelname) s-% (message) s")   #定义日志格式, can write multiple #添加日志格式到ch, Fhch.setformatter ( Formatter) Fh.setformatter (formatter) #添加ch, FH to Logger logger.addhandler (CH) logger.addhandler (FH)  Logger.debug (' Debug Message ') Logger.info (' info message ') Logger.warn (' Warn message ') logger.error (' Error message ') Logger.critical (' critical message ')

The global log level is the bottom line of the entire program, and the local log level is no lower than this level to print.

Screen printing information

2016-10-31 17:23:42,988-test_log-info-info message2016-10-31 17:23:42,988-test_log-warning-warn message2016-10 -31 17:23:42,988-test_log-error-error message2016-10-31 17:23:42,988-test_log-critical-critical Message

Access.log:

2016-10-31 17:02:06,223-test_log-warning-warn message2016-10-31 17:02:06,224-test_log-error-error message2016- 10-31 17:02:06,224-test_log-critical-critical Message

Log all formats:

Important several formats:% (Lineno) d output Print log code line,% (process) d output print log process id,% (thread) d output print log thread ID

  • 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.