Logging Module Introduction
Python's logging module provides a common logging system that can be easily used by third-party modules or applications. This module provides different log levels and can record logs in different ways, such as files, HTTP get/post,smtp,socket, etc., and can even implement specific logging methods on their own.
The logging module is the same as the log4j mechanism, but the specific implementation details are different. module provides logger,handler,filter,formatter.
- Logger: Provides a log interface for use in code. There are two types of logger for the longest operation: configuring and sending log messages. The Logger object can be obtained by Logging.getlogger (name), and if you do not specify name, the root object is returned, and multiple times using the same name calls the GetLogger method to return the same logger object.
- Handler: sends a log record to the appropriate destination (destination), such as a file, socket, etc. A Logger object can add 0 to multiple handler through the AddHandler method, and each handler can also define different log levels for the log rating filtering display.
- Filter: Provides an elegant way to determine whether a log record is sent to handler.
- Formatter: Specifies the specific format of the logging output. The formatter method requires two parameters: the format string of the message and the date string, both of which are optional.
Similar to log4j, calls to Logger,handler and log messages can have specific log levels (level), only at levels greater than logger and handler for log messages.
Logging usage Analysis
1. Initialize logger = Logging.getlogger ("Endlesscode"), the GetLogger () method is best followed by the name of the module to be logged, the following log format of% (name) s corresponds to the module name here
2. Set the level Logger.setlevel (logging. Debug), logging has NotSet < DEBUG < INFO < WARNING < ERROR < Critical these levels, logging records above the set level
3. Handler, commonly used is streamhandler and filehandler,windows under you can simply understand as a console and file log, a print on the cmd window, a record on a file
4. Formatter, which defines the order, structure and content of the final log information, I like to use such formats as ' [% (asctime) s] [% (levelname) s]% (message) s ', '%y-%m-%d%h:%m:%s ',
% (name) s logger name
% (levelname) s log level in text form
% (message) s user-output message
% (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
% (Levelno) s log level in digital form
% (pathname) s calls the full pathname of the module of the log output function and 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 Call the function name of the log output function
% (Lineno) d The line of code where the statement of the log output function is called
% (created) F current time, represented by the UNIX standard floating-point number representing the time
% (relativecreated) d when the log information is output, the number of milliseconds since logger was created
% (thread) d thread ID. Probably not.
% (threadname) s thread name. Probably not.
% (process) d process ID. Probably not.
5. Record logs using Object.debug (message)
Below to write an instance, in the CMD window only the error above the level of the log, but in the log to play debug above the information
Import Logginglogger = Logging.getlogger ("Simple_example") logger.setlevel (logging. Debug) # Set up a Filehandler to log records in the file at level debug FH = logging. Filehandler ("Spam.log") fh.setlevel (logging. DEBUG) # Set up a streamhandler to put the log on the cmd window, level error above ch = logging. Streamhandler () Ch.setlevel (logging. ERROR) # Set the log format formatter = logging. Formatter ("% (asctime) s-% (name) s-% (levelname) s-% (message) S") Ch.setformatter (Formatter) fh.setformatter (Formatter ) #将相应的handler添加在logger对象中logger. AddHandler (CH) logger.addhandler (FH) # Start logging logger.debug ("debug Message") Logger.info ("info message") Logger.warn ("Warn message") Logger.error ("error message") Logger.critical ("Critical Message ")
Run a bit and you'll see that the cmd window records only two, and five logs are recorded in the Spam.log.
When a project is large, log is used in different files, and you can consider encapsulating it as a class to use
#! /usr/bin/env python#coding=gbkimport logging,osclass logger:def __init__ (self, path,clevel = logging. Debug,flevel = logging. DEBUG): Self.logger = Logging.getlogger (path) self.logger.setLevel (logging. DEBUG) FMT = logging. Formatter (' [% (asctime) s] [% (levelname) s]% (message) s ', '%y-%m-%d%h:%m:%s ') #设置CMD日志 sh = logging. Streamhandler () sh.setformatter (FMT) sh.setlevel (clevel) #设置文件日志 fh = logging. Filehandler (Path) fh.setformatter (FMT) fh.setlevel (flevel) self.logger.addHandler (SH) self.logger.addHandler (FH) def debug (self,message): Self.logger.debug (message) def info (self,message): Self.logger.info (Message) def war (self, Message): Self.logger.warn (message) def error (Self,message): Self.logger.error (message) def CRI (self,message): Self.logger.critical (message) if __name__ = = ' __main__ ': Logyyx = Logger (' Yyx.log ', logging. Error,logging. Debug) Logyyx.debug (' A debug Message ') Logyyx.info (' an info message ') Logyyx.war (' A warning message ') logyyx.error (' An error message ') LOGYYX.CRI (' A deadly critical message ')
So that every time you use it, you just instantiate an object.
Logobj = Logger (' filename ', clevel,flevel)
If you want the log of error in the CMD window to be marked red, the warning log is yellow, then you can use the cTYPES module
#! /usr/bin/env python#coding=gbkimport Logging,osimport ctypesforeground_white = 0x0007foreground_blue = 0x01 # text color Contains blue. foreground_green= 0x02 # text color contains GREEN. foreground_red = 0x04 # text color contains RED. Foreground_yellow = foreground_red | foreground_greenstd_output_handle= -11std_out_handle = Ctypes.windll.kernel32.GetStdHandle (std_output_handle) def Set_color (color, handle=std_out_handle): bool = Ctypes.windll.kernel32.SetConsoleTextAttribute (handle, color) return Boolclass logger:def __init__ (self, path,clevel = logging. Debug,flevel = logging. DEBUG): Self.logger = Logging.getlogger (path) self.logger.setLevel (logging. DEBUG) FMT = logging. Formatter (' [% (asctime) s] [% (levelname) s]% (message) s ', '%y-%m-%d%h:%m:%s ') #设置CMD日志 sh = logging. Streamhandler () sh.setformatter (FMT) sh.setlevel (clevel) #设置文件日志 fh = logging. Filehandler (Path) fh.setformatter (FMT) fh.setlevel (flevel) self.logger.addHandler (SH) self.logger.addHandler (FH) def debug (self,message): Self.logger.debug (message) def info (self,message): Self.logger.info (Message) def war (self,message,color= Foreground_yellow): Set_color (color) self.logger.warn (message) Set_color (foreground_white) def error (Self,message, color=foreground_red): Set_color (color) self.logger.error (message) Set_color (foreground_white) def CRI (self,message ): self.logger.critical (message) if __name__ = = ' __main__ ': Logyyx = Logger (' Yyx.log ', logging. Warning,logging. Debug) Logyyx.debug (' A debug Message ') Logyyx.info (' an info message ') Logyyx.war (' A warning message ') logyyx.error (' An error message ') LOGYYX.CRI (' A deadly critical message ')
Multi-Module Use logging
The logging module guarantees that multiple calls to Logging.getlogger (' log_name ') within the same Python interpreter will return the same logger instance, even in the case of multiple modules. So the typical multi-module scenario using logging is to configure logging in the main module, which will be used for multiple submodules, and then get logger objects directly through GetLogger in other modules.
Configuration file:
[Loggers] Keys=root,main [handlers] Keys=consolehandler,filehandler [formatters] keys=fmt [logger_ Root] level=debug handlers=consolehandler [Logger_main] level=debug qualname=main handlers=filehandler [ Handler_consolehandler] Class=streamhandler level=debug formatter=fmt args= (sys.stdout,) [Handler_fileHandler] Class=logging.handlers.rotatingfilehandler level=debug formatter=fmt args= (' Tst.log ', ' a ', 20000, 5,)
Main module main.py:
Import logging Import logging.config logging.config.fileConfig (' logging.conf ') Root_logger = Logging.getlogger (' Root ') Root_logger.debug (' Test root logger ... ') logger = Logging.getlogger (' main ') logger.info (' Test main logger ') Logger.info (' Start import module \ ' mod\ ' ... ') import mod logger.debug (' let\ ' s Test mod.testlogger () ') Mod.testlogger ()
Sub-module mod.py:
Import logging Import submod logger = Logging.getlogger (' Main.mod ') logger.info (' Logger of mod say something ... ')
def Testlogger (): logger.debug (' This is mod.testlogger ... ')
Double module submod.py:
Import logging logger = Logging.getlogger (' Main.mod.submod ') logger.info (' Logger of submod say something ... ') Def TST ():
Then run the Python main.py, console output:
It can be seen, as expected, and then look at the destination of the output in the Tst.log,logger configuration:
Tst.log does not have root logger output information, because LOGGING.CONF is configured with only main logger and its child logger using Rotatingfilehandler, and root logger is output to standard output.