python打开串口时怎么设置停止位_python:每当我想要时如何启动和停止记录器

I am trying to log sql statements in a code in my Django Application

Currently i am using the following logger config in my settings.py

LOGGING = {

'version': 1,

'disable_existing_loggers': False,

'formatters': {

'sql': {

'()': SQLFormatter,

'format': '[%(duration).3f] %(statement)s',

},

'verbose': {

'format': '%(levelname)s %(funcName)s() %(pathname)s[:%(lineno)s] %(name)s \n%(message)s'

}

},

'handlers': {

'console': {

'level': 'DEBUG',

'formatter': 'verbose',

'class': 'logging.StreamHandler',

},

'sql': {

'class': 'logging.StreamHandler',

'formatter': 'sql',

'level': 'DEBUG',

}

}

}

In genereal to log sql in django we can add the django.db.backends to the logger.config in the settings.py

'loggers': {

'django.db.backends': {

'handlers': ['sql'],

'level': 'DEBUG',

'propagate': False,

},

But the problem is it will log every sql statement. So how can we start and stop logging for django.db.backends in between code.

I have the following code in my views.py

def someview(request)

# start logging from here

user_set = User.objects.all()

for user in user_set:

print(user.last_name)

# stop logging from here

Also I want to use the sql handler which I defined in the logging config.

What code will go in start and stop logging place in the above view function.

解决方案

Create a filter class and add an instance to the logger or handler.

class LoggerGate:

def __init__(self, state='open'):

self.state = state

def open(self):

self.state = 'open'

def close(self):

self.state = 'closed'

def filter(self, record):

return self.state == 'open'

Create a filter, initialized in the 'closed' state.

Get the 'django.db.backends' logger and add the filter.

gate = LoggerGate('closed')

sql_logger = logging.getLogger('django.db.backends')

sql_logger.addFilter(gate)

Then call the open or close method to limit logging to where you want it.

def someview(request)

gate.open() # start logging from here

user_set = User.objects.all()

for user in user_set:

print(user.last_name)

gate.close() # stop logging here

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值