#!/usr/bin/env python# Encoding:utf-8import logging# defines the handler output format formatter=logging. The Formatter ('% (asctime) s--% (name) s--% (filename) s--% (message) s ') #创建一个handler to write to the log file, outputting only log fh=logging above the debug level. The Filehandler (' Test.log ') fh.setformatter (formatter) #再创建一个handler for output to the console ch=logging. Streamhandler () Ch.setformatter (formatter) #创建一个logging命名为mylogger,% (name) s can call this name Logger=logging.getlogger (' MyLogger ') Logger.setlevel (logging. DEBUG) #给logger添加handlerlogger. AddHandler (FH) logger.addhandler (CH) #记录两条日志logger. info (' Foorbar ') logger.debug (' Just a test ') [[email protected] ~/documents/python/reboot]$ python loggers.py2017-03-01 15:21:22,434-- mylogger--loggers.py--foorbar2017-03-01 15:21:22,435--mylogger--loggers.py--just a test
Logging Parameters of Formatter:
% (name) s name of the logger (logging channel)
% (Levelno) s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL)
% (levelname) s Text logging level for the message ("DEBUG", "INFO" "WARNING", "ERROR", "CRITICAL")
% (pathname) s full pathname of the source file where the logging is issued (if available)
% (filename) s filename portion of pathname
% (module) s module (name portion of filename)
% (Lineno) d Source Line number where the logging call is issued (if available)
% (funcName) s Function name
% (created) f time when the LogRecord is created (Time.time () return value)
% (asctime) s textual time when the LogRecord is created
% (msecs) d millisecond portion of the creation time
% (relativecreated) d time in milliseconds when the LogRecord is created, relative to the time of the logging module was Loade D (typically at application startup time)
% (thread) d thread ID (if available)
% (threadname) s Thread name (if available)
% (process) d process ID (if available)
% (message) s The result of Record.getmessage (), computed just as the record is emitted
Function Encapsulation Logging Log call
The log log call is encapsulated in the loggers.py. The contents are as follows:
Import loggingdef initlogger (filename,level,name): # create a logging object logger = Logging.getlogger () logger.setlevel (level) #format log file Formatter = logging. Formatter ('% (asctime) s % (name) s-% (levelname) s-% (filename) s-[line:% (Lineno) s]: % (message) s ') #create the logging file handler and Format the log file fh = logging. Filehandler (filename,mode= ' A + ') fh.setformatter (formatter) #create logging print Stream &nbsP; ch = logging. Streamhandler () ch.setformatter (formatter) #logger object load the hander logger.addhandler (FH) logger.addhandler (CH) return logger
Call log:
Import Loggers,logginglogger=loggers. Initlogger ('./testfile.log ', logging.info, ' Test ') logger.info ("Print INFO level log one line")
View Testfile.log log files
[email protected] ~/documents/python/reboot]$ cat testfile.log2017-03-01 15:45:15,974 Root-info-sys.py-[line:6]: Print Info level log one line
method Two: Basic Demo
#filename: Loggers.pydef loggingdemo (): initlogging ('./test.log ') logging.debug ("This is debug message") logging.info ("This is info message ") logging.warning (" This is warning message ") logging.error ("This is error message") def initlogging (LogFileName) : logging.basicconfig (level=logging. debug, format= '% (asctime) s % (name) s-% (levelname) s-% ( FileName) s-[line:% (Lineno) s]: % (message) s ', datefmt= Logfilename, filemode= ' W ', filename=logfilename ); if __name__== ' __main__ ' : loggingdemo ()
Basicconfig Parameters:
filename Specifies that a filehandler is created, using the specified filename, rather than a streamhandler.
FileMode Specifies the mode to open the file, if filename is specified (if FileMode was unspecified, it defaults to ' a ').
Format use the specified format string for the handler.
DATEFMT use the specified date/time format.
Level Set The root logger level to the specified level.
Stream use the specified stream to initialize the Streamhandler. Note that this argument is incompatible with ' filename '-if both was present, ' stream ' is ignored.
Call:
#!/usr/bin/env python# encoding:utf-8import loggers,loggingloggers. Loggingdemo ()
Recommended Way of Use:
import logging,logging.handlers ' ideas 1, through a function, instantiates a logger object 2, the function instantiates the Logger object, and returns a value to the object's seat, which is return logger 3, the other modules directly call the function in the module, Easy " #定义写日志的函数, Returns an instantiated logger object, directly configuring the form of the logger parameter Def writelog (log_name): log_filename= './test.log ' log_level=logging. Debug format = logging. Formatter ('% (asctime) s % (name) s-% (levelname) s-% (filename) s-[line:% (Lineno) s]: % (message) s ') handler = logging.handlers.rotatingfilehandler (log_filename,mode= ' a ', maxBytes=10* 1024*1024,backupcount=5) handler.setformatter (format) logger = logging.getlogger (log_name) logger.addhandler (handler) logger.setlevel (Log_level)    &Nbsp;return loggerif __name__== ' __main__ ': writelog (' API '). Info (' This is test ')
Call:
#!/usr/bin/env python# encoding:utf-8import loggers,loggingloggers. Writelog (' api-2 '). info (' sys file test log ')
Configure logger as a configuration file:
Logger.conf:
#定义logger模块, Root is the parent class, must exist, and the other is the custom #logging.getlogger (NAME) is equivalent to registering the logging module with an instantiated #name, representing the inheritance relationship of log [loggers] Keys=root,exp01,exp02#[logger_xxx] logger_ Module name #level level, level has debug,info,warning,error,critical# handlers processing class, can have multiple, separated by commas #qualname logger name, the application obtains through Logging.getlogger. For names that cannot be obtained, log to the root module #propagate Whether to inherit the log information of the parent class, 0: No, 1: yes [LOGGER_ROOT]LEVEL=DEBUGHANDLERS=HAND01,HAND02 [LOGGER_EXP01]HANDLERS=HAND01, HAND02QUALNAME=EXP01PROPAGATE=0 [LOGGER_EXP02]HANDLERS=HAND01,HAND02QUALNAME=EXP02#[HANDLER_XXX] #class handler class name #level log level #formatter Formatter#args handler initialization function parameter defined above [handlers]keys= Hand01,hand02 [handler_hand01]class=streamhandlerlevel=infoformatter=form02args= (Sys.stderr,) [ handler_hand02]class=filehandlerlevel=debugformatter=form01args= (' Test.log ', ' a ') #和上边的格式一样formatter_XXX Used to format the log [formatters]keys=form01,form02 [formatter_form01]format=% (asctime) s % (name) s-% (levelname) s-% ( FileName) s-[line:% (Lineno) S]: % ( Message) sdatefmt=%a,%d %b %y %h:%m:%s [formatter_form02]format=% (asctime) s % (name) s- % (levelname) s-% (filename) s-[line:% (Lineno) s]: % (message) sdatefmt=%a,%d %b %y %h:%m:%s
Configuration file reads:
#!/usr/bin/env python# encoding:utf-8import logging,logging.configlogging.config.fileconfig ("logger.conf") # config file name logger = Logging.getlogger ("Exp01") # Call the log template, the default must be Rootlogger.debug (' This is Debug ') Logger.info (' This is info ') Logger.warning (' This is warning ')
Execution output:
[email protected] ~/documents/python/reboot]$ python sys.pythu,02 Mar 14:29:04 Exp01-info-sys.py-[line:7]: This is infothu,02 Mar 14:29:04 Exp01-warning-sys.py-[line:8]: This is WARNING
File output:
[email protected] ~/documents/python/reboot]$ cat test.logthu,02 Mar 14:03:41 Exp01-debug-sys.py-[line:6]: This is debugthu,02 Mar 14:03:41 Exp01-info-sys.py-[line:7]: This is infothu,02-14:03:41 exp01-warning-sys.py-[line : 8]: This is warning
Original address: https://www.aolens.cn/?p=1251
This article is from the "Aolens blocks until those" blog, be sure to keep this source http://aolens.blog.51cto.com/7021142/1902668
Python's logging module uses