### 7.11 单例模式
- 无论实例化多少次,永远用的都是第一次实例化出来的对象
```python
class Foo:
pass
#多例,每实例化一次就会创建一个新的对象
obj1 = Foo()
obj2 = Foo()
#单例,无论实例化多少次,都是用的第一次创建的那个对象
```
#### 7.11.1单例模式标准
```python
class Singleton(object):
instance = None
def __new__(cls,*args,**kwargs):
if not cls.instance:
cls.instance= object.__new__(cls)
return cls.instance
obj1 = Singleton()
obj2 = Singleton()
```
文件的连接池
```python
class Filehelper(object):
instance = None
def __init__(self,path)
self.file_object = open(path,mode='r',encoding='utf-8')
def __new__(cls,*args,**kwargs):
if not cls.instance:
cls.instance = object.__new__(cla)
return cls.instance
obj1 = Filehelper('x')
obj2 = Filehelper('x')
```
通过模块导入的特性也可以实现单例模式:
```python
#jd.py
class Foo:
pass
obj = Foo()
```
```python
#app.py
import jd #加载jd.py,在加载最后会实例化一个Foo对象并赋值给obj
print(jd.obj)
```
### 7.12 日志
日志的处理本质
```python
file_handler1 = logging.FileHandler('x2.log', 'a', encoding='utf-8')
fmt1 = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")
file_handler1.setFormatter(fmt1)
logger = logging.Logger('xxxxxx', level=logging.ERROR)
logger.addHandler(file_handler1)
# logger.addHandler(file_handler2)
logger.error('你好')
```
基本格式
```python
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
)
#缺点是只能对一个文件进行操作(公司里不使用),推荐使用下面的的推荐方法
```
推荐处理日志方法
```python
import logging
file_handler = logging.FileHandler(filename='x1.log',mode='a',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
)
logging.error('你好')
```
推荐处理日志方式+日志分割
```python
import time
import logging
for logging import handlers
file_handler = handlers.TimeRotatingFileHandler(filename ='x2.log',when='s',interval=5,encoding='utf-8')
#这里的s是指以秒分割的基本单位,5是指每隔5秒分割一次
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,1000):
time.sleep(1)
logging.error(str(i))
```
注意事项:
```python
#在应用日志时候,如果想要保留异常的堆栈信息(其实就是报在第几行出去,出错原因是啥,就是pycharm的报错样式)
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:
requsts.get('http://www.xx.com')
except Exception as e:
msg = str(e)#调用e.__str__方法
logging.error(msg,exc_info=True)
#转化成字符串后,加入exc_info=True即可
```