一、快速入门
1、基础知识
日志的作用是跟踪,django项目中不可缺少。
派出:
控制台输出:print()
报告事件,发生在一个程序的正常运行:logging.info()或logging.debug()
发出警告关于一个特定的运行时事件:warnings.warn()或logging.warning()
报告一个错误对于一个特定的运行时事件:异常处理
报告一个错误当没有引发一个异常:logging.error()、logging.exception()或logging.critical()
级别:
DEBUG:详细的信息,通常只出现在诊断问题上
INFO:确认一切按预期运行
WARNING:一个迹象表明,一些意想不到的事情发生了,或表明一些问题在不久的将来(例如。磁盘空间低”)。这个软件还能按预期工作。
ERROR:个更严重的问题,软件没能执行一些功能
CRITICAL:一个严重的错误,这表明程序本身可能无法继续运行
日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRITICAL。这5个等级,也分别对应5种打日志的方法: debug 、info 、warning 、error 、critical。默认的是WARNING,当在WARNING或之上时才被跟踪。有两种方式记录跟踪,一种输出控制台,另一种是记录到文件中,如日志文件。
2、简单日志操作
1
2
3
|
import logging
logging.warning( 'error' ) #在控制台输出WARNING:root:error
logging.info( 'msg' ) #没有输出,因为默认级别是 WARNING,INFO小于此级别
|
写入一个文件里面:
#Logging to a file
import os
import logging
FILE = os.getcwd()
logging.basicConfig(filename=os.path.join(FILE,'log.txt'),level=logging.DEBUG)
logging.debug('写进去')
logging.info('滚进去')
logging.warning('也滚进去')
运行之后,打开该文件,效果如下:
3、多个模块中操作日志
import logging
def lo():
logging.info('log1--')
import logging
import os
FILE = os.getcwd()
import log1
def main():
logging.basicConfig(filename=os.path.join(FILE,'log.txt'),level=logging.INFO)
logging.info('start--')
log1.lo()
logging.info('end--')
if __name__ == '__main__':
main()
运行后打开log.txt,结果如下:
INFO:root:start--
INFO:root:log1--
INFO:root:end--
一、模块级函数
除了上面描述的类,有许多模块级功能。
1、logging.getLogger([name])
见上小节
2、logging.debug(msg[,*args[,*kwargs]])
在 root logger 上记录消息以level DEBUG;
msg:表示消息格式字符串。
args:作用于msg,是使用字符串格式操作符(注意,这意味着您可以使用关键字的格式字符串,连同一个字典参数。)
kwargs:两个关键字参数,exc_info.
exc_info which, if it does not evaluate as false, causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) is provided, it is used; otherwise, sys.exc_info() is called to get the exception information.
另一个参数是extra,which can be used to pass a dictionary which is used to populate(填充) the __dict__ of the LogRecord created for the logging event with user-defined attributes.
import logging
FORMAT = '%(asctime)s:[%(IP)s--%(user)-8s]%(message)s'
logging.basicConfig(format=FORMAT)
d = {'IP':'192.168.0.1','user':'BeginMan'}
logging.warning('msg:%s','OK',extra=d) #2013-09-23 15:58:31,619:[192.168.0.1--BeginMan]msg:OK