前言
Sanic没有像Flask那么优秀的集成了logging。但是项目中日志功能又必不可少。所以就来学习下
首先是官方的一个例子
from sanic import Sanic
from sanic.config import LOGGING
# The default logging handlers are ['accessStream', 'errorStream']
# but we change it to use other handlers here for demo purpose
LOGGING['loggers']['network']['handlers'] = [
'accessSysLog', 'errorSysLog']
app = Sanic('test')
@app.route('/')
async def test(request):
return response.text('Hello World!')
if __name__ == "__main__":
app.run(log_config=LOGGING)
```
### 可以看出,sanic有关于对logging的配置。但是如果像Flask中直接使用的话,还需要改造一下。
```python
from sanic.response import json
from sanic import Sanic
from sanic.config import LOGGING
import logging
class sanic(Sanic):
def __init__(self,*args,**kwargs):
super(sanic,self).__init__(*args,**kwargs)
self.web_app = Sanic(__name__)
self.web_app.config.LOGO = None
self.web_app.log_config = LOGGING
self.web_app.logger = self.logger()
def logger(self):
return logging.getLogger('sanic')
def create_app(self):
return self.web_app
@app.route('/')
async def get(request):
current_app = request.app
current_app.logger.debug('111111111111111111111111111111111111111111111111111111111111111111')
return json({1: 2})
if __name__ == '__main__':
app = sanic().create_app()
app.run(debug=True)
```
#### 继承一个sanic的类,然后给他一个logging的属性。这样就可以像FLask一样的使用了