Python全局变量意外变化
我有这个代码应该登录到内存变量: (the_message_lines):
import logging
from thompcoutils import log_utils
the_message_lines = []
class MemoryHandler(logging.StreamHandler):
"""
Handler that keeps all log messages in memory until the beginning of the day or the size exceeds a value
"""
def emit(self, record: logging.LogRecord):
global the_message_lines
try:
msg = self.format(record)
the_message_lines.append(msg)
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
@staticmethod
def get_lines():
return the_message_lines
@staticmethod
def reset_lines():
global the_message_lines
the_message_lines.clear()
if __name__ == '__main__':
log_utils.load_log_config('logging.ini')
logger = log_utils.get_logger()
logger.warning('beginning')
for i in range(3):
lines = MemoryHandler.get_lines()
logger.warning('remaining %d seconds', i, extra={'same_line':True})
logger.warning('end')
for line in MemoryHandler.get_lines():
print(line)
它的行为应有的行为,但是如果我在emit方法中放一个断点并观察the_message_lines,则the_message_lines来(?)
,它每次都会累积日志消息。 如果我在记录的循环中放置一个断点,则每次都有the_message_lines是空的! 因此,在日志请求之间,the_message_lines似乎删除了自身,但是在EMIT中,它很好。 在main()方法的末尾,get_lines()返回一个空数组。
我想念什么?
I have this code that is supposed to log to a memory variable:
(the_message_lines):
import logging
from thompcoutils import log_utils
the_message_lines = []
class MemoryHandler(logging.StreamHandler):
"""
Handler that keeps all log messages in memory until the beginning of the day or the size exceeds a value
"""
def emit(self, record: logging.LogRecord):
global the_message_lines
try:
msg = self.format(record)
the_message_lines.append(msg)
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
@staticmethod
def get_lines():
return the_message_lines
@staticmethod
def reset_lines():
global the_message_lines
the_message_lines.clear()
if __name__ == '__main__':
log_utils.load_log_config('logging.ini')
logger = log_utils.get_logger()
logger.warning('beginning')
for i in range(3):
lines = MemoryHandler.get_lines()
logger.warning('remaining %d seconds', i, extra={'same_line':True})
logger.warning('end')
for line in MemoryHandler.get_lines():
print(line)
It behaves as it should but the_message_lines come and go(?)
If I put a break point in the emit method and observe the_message_lines, it behaves as it should, accumulating log messages every time.
If I put a break point in the loop that is logging, the_message_lines is empty every time!
So, between log requests, the_message_lines appears to delete itself, but in the emit, it is fine.
At the end of the main() method, get_lines() returns an empty array.
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论