Sanic框架之日志记录

前言

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一样的使用了

转载于:https://my.oschina.net/u/2333235/blog/1529551

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值