python学习day23 logging模块

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)
    
上一篇:shell实战训练营Day23


下一篇:Delphi来实现一个IP地址输入控件