ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python学习day23 logging模块

2019-04-30 16:49:14  阅读:217  来源: 互联网

标签:info logging name format python day23 print import


logging&程序目录结构

0.知识点补充

1.字符串格式化

  1. %s

    #方式1:%s与替换值相对性,构造元组
    msg = "我是%s,年龄%s" %('alex',19,)
    print(msg)
    
    #方式2:%s中间加一个变量,最后构造字典匹配值
    msg = "我是%(n1)s,年龄%(n2)s" % {'n1': 'alex', 'n2': 123, }
    print(msg)
    
  2. format

    # v1 = "我是{0},年龄{1}".format('alex',19)
    v1 = "我是{0},年龄{1}".format(*('alex',19,))
    print(v1)
    
    # v2 = "我是{name},年龄{age}".format(name='alex',age=18)
    v2 = "我是{name},年龄{age}".format(**{'name':'alex','age':18})
    print(v2)
    

2.有序字典Orderedict

from collections import OrderedDict

info = OrderedDict()
info['k1'] = 123
info['k2'] = 456

print(info.keys())
print(info.values())
print(info.items())

3.栈和队列

class Stack(object):
    pass

class Queue(object):
    pass

4.反射

class Foo(object):
    def get(self):
        pass

obj = Foo()
# if hasattr(obj,'post'): 
#     getattr(obj,'post')

v1 = getattr(obj,'get',None) # 推荐
print(v1)

5.nametuple可命名元组

from collections import namedtuple   # 可命名元组
Course = namedtuple('Course',['name','price','teacher'])
python = Course('python',19800,'alex')
print(python)
print(python.name)
print(python.price)
    # 创建一个类,这个类没有方法,所有属性的值都不能修改

1.单例模式

  • 单例模式: 无论实例化多少次,都用第一次实例化的对象.

  • 标准格式

    • __new__创建一个实例化对象,并且在init之前执行
    class Singleton(object):
        instance= None
        def __new__ (cls,*args,**kwargs):
        	if not cls.instance:
                cls.instance= object.__new__(cls)
            return cls.instance
    

2.logging(日志模块)

  • 快速编写格式(扩展性不强)

    import logging
    import requests
    
    # 日志配置
    logging.basicConfig(
        filename='log.log',
        format=' %(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S %p',
        level=logging.ERROR)
    # 异常处理
    try:
        requests.get('http://www.xxx.com')
    except Exception  as e:
        mes = str(e)
        # 日志生成
        logging.error(mes, ext_info=True)    #ext_info=True保存堆栈信息
    
  • 推荐编写方式

    import logging
    file_hander = logging.FileHandler(filename='log.log',mode='a',encoding='utf-8',)
    logging.basicConfig(
        format=%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
        datafmt='%Y-%m-%d %H:%M:%S %p',
        handlers=[file_handler,],
        level=logging.ERROR
    )
    
    logging.error('你好')
    
  • 更改调用机制:

    import logging
    
    def get_logger():
        file_hander = logging.FileHandler(filename='log.log',mode='a',encoding='utf-	8',)
        logging.basicConfig(
            format=%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
            datafmt='%Y-%m-%d %H:%M:%S %p',
            handlers=[file_handler,],
            level=logging.ERROR
        )
    	return logging
    logger = get_logger()
    
    
    logging.error('你好')
    
  • 推荐日志处理方式+日志切割

    import time
    import logging
    from logging import handlers
    
    file_handler = handlers.TimedRotatingFileHandler(filename='x3.log', when='s', interval=5, encoding='utf-8')
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S %p',
        handlers=[file_handler,],
        level=logging.ERROR
    )
    
    for i in range(1,100000):
        time.sleep(1)
        logging.error(str(i))
    
  • 注意事项

    # 在应用日志时,如果想要保留异常的堆栈信息。
    import logging
    import requests
    
    logging.basicConfig(
        filename='wf.log',
        format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S %p',
        level=logging.ERROR
    )
    
    try:
        requests.get('http://www.xxx.com')
    except Exception as e:
        msg = str(e) # 调用e.__str__方法
        logging.error(msg,exc_info=True)
    

标签:info,logging,name,format,python,day23,print,import
来源: https://blog.csdn.net/weixin_43240734/article/details/89712035

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有