![](/img/trans.png)
[英]How to get the level of the logging record in a custom logging.Handler in Python?
[英]Making a logging.Handler with async emit
我有一個 Python 日志處理程序,它使用 asyncio 寫入(以任何其他方式寫入此特定服務的工作量太大)。 我還希望能夠記錄來自后台線程的消息,因為一些代碼可以做到這一點。 所以我的代碼基本上是這樣的(最小版本):
class AsyncEmitLogHandler(logging.Handler):
def __init__(self):
self.loop = asyncio.get_running_loop()
super().__init__()
def emit(self, record):
self.format(record)
asyncio.run_coroutine_threadsafe(
coro=self._async_emit(record.message),
loop=self.loop,
)
async def _async_emit(message):
await my_async_write_function(message)
大多數情況下它工作正常但是當進程退出時我收到很多這樣的警告:“coroutine 'AsyncEmitLogHandler._async_emit' was never awaited”
關於更清潔的方法有什么建議嗎? 或者某種方式來捕獲關閉並殺死掛起的寫入? 或者只是抑制警告?
注意:完整代碼在[此處][1][1]:https://github.com/lsst-ts/ts_salobj/blob/c0c6473f7ff7c71bd3c84e8e95b4ad7c28e67721/python/lsst/ts/salobj/sal_log_handler.py
您可以保留對 coro 的引用,並覆蓋處理程序的close()
方法以在其上調用close()
。 管理 coros 的一般方法是在處理程序中保留它們的列表,並覆蓋處理程序的close()
方法以在每個 coro 上調用close()
,或者從它們創建任務並在每個任務上調用cancel()
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.