Make sure your Python version > Python 2.3
1 from a small case:
Cat howto_logging.py
#coding=utf8# file name: howto_logging# this file shows how to use logging# made by vasks, email:[email protected]import logging# 创建一个logger,级别:DEBUGlogger = logging.getLogger(‘Err_Logger‘)logger.setLevel(logging.DEBUG)# 创建一个handler,用于写入日志文件fh = logging.FileHandler(‘err.log‘)fh.setLevel(logging.DEBUG)# 再创建一个handler,用于输出到控制台ch = logging.StreamHandler()ch.setLevel(logging.DEBUG)# 定义handler的输出格式formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s - %(lineno)d‘)fh.setFormatter(formatter)ch.setFormatter(formatter)# 给logger添加handlerlogger.addHandler(fh)logger.addHandler(ch)# 记录日志 NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICALlogger.debug(‘just a debug‘)logger.info(‘just a info‘)logger.warning(‘waring,please check out‘)logger.error(‘error,oh no‘)logger.critical("critical,it doesn‘t work")
Terminal output Execution Result:
2015-04-02 17:03:29,421 - Err_Logger - DEBUG - just a debug - 292015-04-02 17:03:29,423 - Err_Logger - INFO - just a info - 302015-04-02 17:03:29,423 - Err_Logger - WARNING - waring,please check out - 312015-04-02 17:03:29,423 - Err_Logger - ERROR - error,oh no - 322015-04-02 17:03:29,423 - Err_Logger - CRITICAL - critical,it doesn‘t work - 33[Finished in 0.1s]
Results of Err.log:
cat err.log2015-04-02 17:03:29,421 - Err_Logger - DEBUG - just a debug - 292015-04-02 17:03:29,423 - Err_Logger - INFO - just a info - 302015-04-02 17:03:29,423 - Err_Logger - WARNING - waring,please check out - 312015-04-02 17:03:29,423 - Err_Logger - ERROR - error,oh no - 322015-04-02 17:03:29,423 - Err_Logger - CRITICAL - critical,it doesn‘t work - 33
2. Logging detailed2.1 Logger: Provides a log interface for use in code. There are two types of logger for the longest operation: configuring and sending log messages.
- Logging.getlogger (name):
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.
- Logger.setlevel (LVL):
The level of the logger is set to the following levels:NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL If the level of Looger is set to INF O, logs that are less than the info level are not output, and logs that are greater than or equal to the info level are output. Less than is not output.
2.2 Handler: Send log records to the appropriate destination, such as files, sockets, 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.
We set up here two, one output to the terminal, one output to the Err.log file.
Handler has the following main types:
Streamhandler: Output to console
Filehandler: Output to File
Handler can also set its own level and output format.
2.3 Filter: Provides an elegant way to determine whether a log record is sent to handler.2.4 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.
More formats:
Format description (what is represented)% (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).% ( FuncName) s Name of function containing the logging call.% ( Lineno) d Source Line number where the logging call is issued (if available).% ( Created) F time when the LogRecord is created (as returned by Time.time ()).% ( relativecreated) d time in milliseconds when the LogRecord is created, relative to the time of the logging module was loaded. % (asctime) s human-readable time when the LogRecord is created. By default this is the form "2003-07-08 16:49:45,896" (The Numbers AFter the comma is millisecond portion of the time).% ( msecs) d millisecond portion of the time when the LogRecord is created.% ( Thread) d thread ID (if available).% ( ThreadName) s Thread name (if available).% ( Process) d process ID (if available).% ( Message) s the logged message, computed as msg% args.
Here are the Chinese:
%(name)s Logger的名字%(levelno)s 数字形式的日志级别%(levelname)s 文本形式的日志级别%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有%(filename)s 调用日志输出函数的模块的文件名%(module)s 调用日志输出函数的模块名%(funcName)s 调用日志输出函数的函数名%(lineno)d 调用日志输出函数的语句所在的代码行%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒%(thread)d 线程ID。可能没有%(threadName)s 线程名。可能没有%(process)d 进程ID。可能没有%(message)s 用户输出的消息
2.5 logging.basicconfig ()2.5.1 Logging.basicconfig ([**kwargs])
This function is used to configure root logger to create a handler for root logger,
Sets the default format.
These functions: Logging.debug (), Logging.info (), logging.warning (),
Logging.error (), logging.critical () If the call finds root logger no
Handler, the basicconfig is automatically called to add a handler
If root logger already has handler, this function doesn't do anything, use Basicconfig to configure the root logger output format and level.
Example:
import logging logging.basicConfig(format=‘%(levelname)s:%(message)s‘, level=logging.DEBUG) logging.debug(‘This message should appear on the console‘)
About root logger and logger's parent-child relationship
The previous mentions of root logger, in fact logger instances have a parent-child relationship, root logger is in
The topmost logger, it is the ancestor of all logger. Such as:
Root logger is the default logger
If you do not create logger instances, call Logging.debug (), Logging.info (), logging.warning (), Logging.error (), logging.critical () directly, Then the logger used is root logger, which can be created automatically and is a single instance.
How to get root logger
The root logger instance is obtained by Logging.getlogger () or Logging.getlogger ("").
The default Level
Root logger The default level is logging. WARNING
How to represent a parent-child relationship
The naming of the logger name can represent a parent-child relationship between logger. Like what:
parent_logger = logging.getLogger(‘foo‘) child_logger = logging.getLogger(‘foo.bar‘)
What is effective level
Logger has a concept called effective level. If a logger does not display the level, then it
With the father's level. If the father does not display the level, just use the father's level to push ....
At the end of the root logger, you must set the level. The default is logging. WARNING
After the child loggers gets the message, both the message is distributed to its handler processing, which is also passed to all ancestors logger processing,
Take a look at an example
import logging# 设置root loggerr = logging.getLogger()ch = logging.StreamHandler()ch.setLevel(logging.DEBUG)formatter = logging.Formatter(‘%(asctime)s - %(levelname)s - %(message)s‘)ch.setFormatter(formatter)r.addHandler(ch)# 创建一个logger作为父亲p = logging.getLogger(‘foo‘)p.setLevel(logging.DEBUG)ch = logging.StreamHandler()ch.setLevel(logging.DEBUG)formatter = logging.Formatter(‘%(asctime)s - %(message)s‘)ch.setFormatter(formatter)p.addHandler(ch)# 创建一个孩子loggerc = logging.getLogger(‘foo.bar‘)c.debug(‘foo‘)
The output is as follows:
2015-04-02 18:44:38,128 - foo2015-04-02 18:44:38,128 - DEBUG - foo[Finished in 0.2s]
As can be seen, the child logger without any handler, so the message is not processed. But it forwarded the message to its father and root logger. Output two logs at the end of the line.
Let's look at an example:
Import Logging # Set up logging to File-see previous sections for more details Logging.basicconfig (level=loggin G.debug, format= '% (asctime) s% (name) -12s% (levelname) -8s% (message) s ', Datef mt= '%m-%d%h:%m ', filename= ' Mylogging.log ', filemode= ' W ') # define a Hand Ler which writes INFO messages or higher to the sys.stderr console = logging. Streamhandler () Console.setlevel (logging. WARNING) # Set a format which is simpler to console use formatter = logging. Formatter ('% (name) -12s:% (levelname) -8s% (message) s ') # tell the handler-use this format console.setformatter (for matter) # Add the handler to the root logger Logging.getlogger ("). AddHandler (console) # Now, we can log to the R Oot logger, or any other logger. First the root ... logging.info (' Jackdaws love my big sphinx of quartz. ') # Now, define a couple of all loggers which might represent areas inYour # Application:logger1 = Logging.getlogger (' myapp.area1 ') Logger2 = Logging.getlogger (' myapp.area2 ') Logg Er1.debug (' Quick zephyrs blow, vexing daft Jim. ') Logger1.info (' How quickly daft jumping zebras vex. ') Logger2.warning (' Jail Zesty vixen who grabbed pay from quack. ') Logger2.error (' The five boxing wizards jump quickly. ')
Terminal output:
myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack. myapp.area2 : ERROR The five boxing wizards jump quickly. [Finished in 0.1s]
Terminal under Streamhandler ():
Logging.info Root own info does not set the level warning large, does not output
Logger1 info and debug do not have the level set: Warning large, so do not output
Logger2 meet the conditions, output
Text output:
04-02 19:15 root INFO Jackdaws love my big sphinx of quartz.04-02 19:15 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.04-02 19:15 myapp.area1 INFO How quickly daft jumping zebras vex.04-02 19:15 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.04-02 19:15 myapp.area2 ERROR The five boxing wizards jump quickly.
The alarm level set in the Basicconfig is debug, so everyone outputs the output to the text.
2.5.1 Detailed Basicconfig Parameters:
filename: 指定日志文件名 filemode: 和file函数意义相同,指定日志文件的打开模式,‘w‘或‘a‘ format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示: %(levelno)s: 打印日志级别的数值 %(levelname)s: 打印日志级别名称 %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0] %(filename)s: 打印当前执行程序名 %(funcName)s: 打印日志的当前函数 %(lineno)d: 打印日志的当前行号 %(asctime)s: 打印日志的时间 %(thread)d: 打印线程ID %(threadName)s: 打印线程名称 %(process)d: 打印进程ID %(message)s: 打印日志信息 datefmt: 指定时间格式,同time.strftime() level: 设置日志级别,默认为logging.WARNING stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略
This article refers to these blogs:
- Http://www.cnblogs.com/captain_jack/archive/2011/01/21/1941453.html
- Http://bbs.chinaunix.net/thread-3590256-1-1.html
- Http://www.cnblogs.com/bjdxy/archive/2013/04/12/3016820.html
Python logging-vasks