设为首页 收藏本站
查看: 1657|回复: 0

[经验分享] Python 模块学习 logging(2)

[复制链接]

尚未签到

发表于 2015-4-22 11:36:16 | 显示全部楼层 |阅读模式
一、模块级函数
  除了上面描述的类,有许多模块级功能。
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
  这里关键字参数传递不能与logging系统的关键字参数冲突。如'message'
3、下同
  logging.info(msg[, *args[, **kwargs]])

logging.warning(msg[, *args[, **kwargs]])logging.error(msg[, *args[, **kwargs]])logging.critical(msg[, *args[, **kwargs]])
4、logging.exception(msg[, *args])
  用法同上上



try:
raise Exception,u'错误异常'
except:
logging.exception('msg:%s','Error')
# ERROR:root:msg:Error
# Traceback (most recent call last):
#   File "E:\project\py\src\log4.py", line 15, in
#     raise Exception,u'错误异常'
# Exception: 错误异常
5、logging.log(level, msg[, *args[, **kwargs]])
  参数用法同logging.debug()



import logging
FORMAT = '%(asctime)s:[%(IP)s--%(user)-8s]%(message)s'
logging.basicConfig(format=FORMAT)
d = {'IP':'192.168.0.1','user':'BeginMan'}
logging.log(logging.DEBUG, 'Great:%s','Python',extra=d)
6、logging.disable(level)
  其作用是禁用所有日志当其级别在给定级及以下,当出现需要暂时截流日志输出下来整个应用程序,这个函数可以是有用的。



logging.disable(logging.WARNING)#提供一个覆盖所有优先于日志级别的级别
logging.warn('msg')     #没有输出
logging.critical('msg') #CRITICAL:msg
  撤销的话,就使用logging.disable(levle)或logging.disable(logging.NOSET)
7、logging.addLevelName(lel,levelname)
  增加自定义的logging level,并起名。



logging.addLevelName(88,'myLevelName')
logging.log(88, '自定义设置级别')  #myLevelName:root:自定义设置级别
  级别是整数,系统设置如下:
DSC0000.jpg
8、logging.getLevelName(lvl)
  返回的文本表示的日志级别



logging.addLevelName(88,'myLevelName')
logging.log(88, '自定义设置级别')             #myLevelName:root:自定义设置级别
print logging.getLevelName(88)              #myLevelName
print logging.getLevelName(logging.INFO)    #INFO
9、logging.basicConfig()
  Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger.
  This function does nothing if the root logger already has handlers configured for it.
  见上节详解。
二、logging.handlers
  接下来学习logging的控制器,有三类:StreamHandler、FileHandler、NullHandler。
  StreamHandler类,在logging包中,发送日志输出流 如sys.stdout
  
  The FileHandler class,发送日志输出到磁盘文件,它继承了StreamHandler输出功能。
    class logging.FileHandler(filename, mode='a', encoding=None, delay=False)
返回一个FileHandler类的实例,如果存在延时(delay=True),那么,文件打开推迟到第一次调用emit()。
它有如下方法:close():关闭一个文件;emit(record):输出文件的记录。



import os
import logging
import datetime
'''FileHandler'''
'''FileHandler类,存在于logging包中,发送日志输出到磁盘文件中,它继承了StreamHandler输出功能。
class logging.FileHandler(filename, mode='a', encoding=None, delay=False)
返回一个FileHandler类的实例,如果存在延时(delay=True),那么,文件打开推迟到第一次调用emit()。
它有如下方法:close():关闭一个文件;emit(record):输出文件的记录。
'''
logger = logging.getLogger()    #生成一个日志对象
hdlr = logging.FileHandler(os.path.join(os.getcwd(),'log.txt'),'w') #返回一个FileHandler对象
formatter = logging.Formatter('%(asctime)s:%(name)s-->%(levelname)s %(message)s')
hdlr.setFormatter(formatter)    #将格式器设置到处理器上
logger.addHandler(hdlr)         #将处理器加到日志对象上
logger.setLevel(logging.NOTSET) #设为NOTSET(值为0),输出所有
try:
lis = []
lis+'s'
print lis
except  Exception,e:
logger.error('出现异常:%s',e)
#打开log.txt文件查看错误:
# 2013-09-23 17:33:16,418:root-->ERROR 出现异常:can only concatenate list (not "str") to list

三、使用fileConfig来使用logger





import logging
import logging.config
logging.config.fileConfig("logging.conf")
# create logger
logger = logging.getLogger("simpleExample")
# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
  logging.conf文件如下:



[loggers]
keys=root,simpleExample
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
  运行结果:
  2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
  参考:http://www.iyunv.com/itech/archive/2011/01/18/1934468.html
四、个人常用



#应用django项目S
import logging
import datetime
LOGDIR = os.path.join(DIRNAME,'log')
LOGFILE = datetime.datetime.now().strftime('%Y-%m-%d')+'.log'
logging.basicConfig(level=logging.DEBUG,
format='',
datefmt='%a, %d %b %Y %H:%M:%S',
filename = os.path.join(LOGDIR,LOGFILE),
filemode='a'
)
fileLog = logging.FileHandler(os.path.join(LOGDIR,LOGFILE),'w')
formatter = logging.Formatter('%(asctime)s %(name)s:%(levelname)s %(message)s')
fileLog.setFormatter(formatter)
logging.getLogger('demo').addHandler(fileLog)
logging.getLogger('demo').setLevel(logging.DEBUG)
logging.getLogger('demo').info(u'项目已启动:')

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-59587-1-1.html 上篇帖子: 深入Python(1): 字典排序 关于sort()、reversed()、sorted() 下篇帖子: pyxml for python 2.6 死而复生
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表