简体   繁体   English

记录错误时Loguru回调function

[英]Loguru callback function when an error is logged

I'm moving a desktop application from Python's standard library logging to Loguru, and want to have a text box in the user interface that contains logging information.我正在将桌面应用程序从 Python 的标准库日志记录移动到 Loguru,并希望在用户界面中有一个包含日志记录信息的文本框。

Is there a way to hook into Loguru error-level logging which allows the log message to be sent to a callback function?有没有办法挂钩 Loguru 错误级别日志记录,允许将日志消息发送到回调 function? This would allow me to update the user interface with the latest error messages.这将允许我使用最新的错误消息更新用户界面。 For example,例如,

from loguru import logger

def error_callback(msg: str):
    # Do something with the error message
    pass

logger.add_callback(error_callback) # <-- Does something like this exist?

# So when I do this...
logger.error("Oh noes")
# ... the callback is called with the argument `"Oh noes"`

You can't add a callback for only errors, but you can add a callback for every log and inside of that check if it is an error.您不能只为错误添加回调,但您可以为每个日志添加回调,并在其中检查它是否是错误。 The idea is the same as Adapters do in stdlib logging, with the only difference that loguru calls it patch .这个想法与适配器在 stdlib 日志记录中所做的相同,唯一的区别是 loguru 称之为patch

from loguru import logger

def error_callback(record):
    if record['level'].name == 'ERROR':
        print('logging an error')
        # the log message is available as: record['message']

logger = logger.patch(error_callback)

logger.error('error')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM