Python logging module
Python logging provides a standard logging interface, and the Python logging log is divided into 5 levels:
debug(), info(), warning(), error() and critical()
Simple usage
import logginglogging.warning("warning.........")logging.critical("server is down")
Print
WARNING:root:warning.........CRITICAL:root:server is down
5 log levels represent the meaning:
| Level
Description |
DEBUG |
Detailed information, typically of interest only when diagnosing problems. |
INFO |
Confirmation that things is working as expected. |
WARNING |
An indication this something unexpected happened, or indicative of some problem in the "near" (e.g. ' disk space low ') . The software is still working as expected. |
ERROR |
Due to a more serious problem, the software have not been able to perform some function. |
CRITICAL |
A serious error, indicating the program itself is unable to continue running. |
Write the log in the file
import logginglogging.basicConfig(filename="log_test.log", level=logging.INFO) #此处定义了日志级别,INFO以及高于INFO的日志会被记录logging.debug("debug..............")logging.info("info..............")logging.warning("warning...........")
Results:
Let's adjust the log level:
import logginglogging.basicConfig(filename="log_test.log", level=logging.DEBUG) #level 改为 debuglogging.debug("debug..............")logging.info("info..............")logging.warning("warning...........")
Results:
The debug level log has been logged. In addition, the log is written in append and does not overwrite the previous log.
Custom log Format
Log format parameters:
% (name) s |
logger name |
% (Levelno) s |
Log level in digital form |
% (LevelName) s |
Log level in text form |
% (pathname) s |
The full path name of the module that called the log output function may not have |
% (filename) s |
The file name of the module that called the log output function |
% (module) s |
Call the module name of the log output function |
% (FuncName) s |
Function name of the call log output function |
% (Lineno) d |
The line of code where the statement that called the log output function is located |
% (created) f |
Current time, represented by the UNIX standard floating-point number representing the time |
% (relativecreated) d |
The number of milliseconds since logger was created when the log information is output |
% (Asctime) s |
The current time in string form. The default format is "2003-07-08 16:49:45,896". The comma is followed by milliseconds |
% (thread) d |
The thread ID. Probably not. |
% (ThreadName) s |
The name of the thread. Probably not. |
% (process) d |
The process ID. Probably not. |
% (message) s |
User-Output messages |
Take a look at the break code:
import logginglogging.basicConfig(filename="log_test.log", level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(module)s - %(lineno)d %(message)s", datefmt="%Y-%m-%d %I:%M:%S:%p" )def fun1(): logging.error("error......")fun1()logging.debug("debug..............")logging.info("info..............")logging.warning("warning...........")
Results:
Advanced usage
1.生成logger对象logger = logging.getLogger("web")logger.setLevel(logging.INFO) #设置日志级别。默认日志级别为 warning# 2.生成handler对象console_handler = logging.StreamHandler() # 用于打印的handlerconsole_handler.setLevel(logging.WARNING) #也可以专门针对 handler设置日志级别file_handler = logging.FileHandler("web.log") # 用于输出到文件的 handlerfile_handler.setLevel(logging.ERROR)# 2.1 把handler 对象 绑定到 loggerlogger.addHandler(console_handler)logger.addHandler(file_handler)# 3.生成formatter 对象console_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")file_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(lineno)s - %(message)s")# 3.1 把formatter 对象 绑定到 handlerconsole_handler.setFormatter(console_formatter)file_handler.setFormatter(file_formatter)logger.info("info----")logger.warning("warning-------------")logger.error("error-------")
The logging level of the global settings, such as log level and handler, is filtered progressively.
Like what:
- The level of the global setting is info, the level of handler setting is debug, and at the end, the debug level logs are filtered out
- The global set of bounds is the level of Info,handler setting is error, and in the end, the error is higher than the error level of the log will be output
Filter log:
# *_*coding:utf-8 *_*import loggingclass ingonrebackuplogfilter (logging. Filter): "" to find logs with DB Backup "" Def filter (self, record): #固定写法 return "DB Backup" in Record.getmessage () # 1. Generate Logger Object logger = Logging.getlogger ("Web") logger.setlevel (logging. DEBUG) #设置日志级别. The default log level is warning# 1.1 to add the filter object to Logger Logger.addfilter (Ingonrebackuplogfilter ()) # 2. Generate Handler Object Console_handler = Logging. Streamhandler () # Handlerfile_handler = logging for printing. Filehandler ("Web.log") # handler# for output to file 2.1 bind handler object to Loggerlogger.addhandler (Console_handler) Logger.addhandler (File_handler) # 3. Generate Formatter Object console_formatter = logging. Formatter ("% (asctime) s-% (name) s-% (levelname) s-% (message) s") File_formatter = logging. Formatter ("% (asctime) s-% (name) s-% (levelname) s-% (Lineno) s-% (message) S") # 3.1 bind the Formatter object to the Handlerconsole_handl Er.setformatter (Console_formatter) file_handler.setformatter (file_formatter) logger.info ("info----") Logger.warning ("Warning-------------") logger.error ("ErroR-------") Logger.error (" Error db Backup----") # Print: # 2018-07-08 20:10:40,023-web-error-error DB Backup----
Automatic file truncation:
import loggingfrom logging import handlerslogger = logging.getLogger(__name__)log_file = "timelog.log"# file_handler = handlers.RotatingFileHandler(filename=log_file, maxBytes=10, backupCount=3) file_handler = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3)formatter = logging.Formatter('%(asctime)s - %(module)s - %(lineno)d - %(message)s')file_handler.setFormatter(formatter)logger.addHandler(file_handler)logger.warning("test1")logger.warning("test2")logger.warning("test3")logger.warning("test4")
Result: Different log files will be generated on time:
file_handler = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3)
can use the? when? To specify the type? interval. The list of possible values is below. Note that they is not case sensitive.
(You can use when to specify the type of interval.) A list of possible values is as follows. Note that they are not case-sensitive. )
(This English is still necessary to take time to do it.)
Value |
Type of Interval |
‘S‘ |
Seconds |
‘M‘ |
Minutes |
‘H‘ |
Hours |
‘D‘ |
Days |
‘W‘ |
Week Day (0=monday) |
‘midnight‘ |
Roll over at midnight Midnight roll Over |
Python logging-module