{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 日志视图\n", "\n", "创建一个日志视图,允许添加新行而无需将整个历史记录重新发送给客户端。\n", "\n", "`max_lines`: 在丢弃最旧的行之前的最大行数(默认:`None`)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from datetime import datetime\n", "from nicegui import ui\n", "\n", "log = ui.log(max_lines=10).classes('w-full h-20')\n", "ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime('%X.%f')[:-5]))\n", "\n", "# ui.run()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 附加日志\n", "\n", "你可以将一个`ui.log`元素附加到一个Python日志记录器对象上,这样日志消息就会被推送到日志元素中。" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import logging\n", "from datetime import datetime\n", "from nicegui import ui\n", "\n", "logger = logging.getLogger()\n", "\n", "class LogElementHandler(logging.Handler):\n", " \"\"\"A logging handler that emits messages to a log element.\"\"\"\n", "\n", " def __init__(self, element: ui.log, level: int = logging.NOTSET) -> None:\n", " self.element = element\n", " super().__init__(level)\n", "\n", " def emit(self, record: logging.LogRecord) -> None:\n", " try:\n", " msg = self.format(record)\n", " self.element.push(msg)\n", " except Exception:\n", " self.handleError(record)\n", "\n", "log = ui.log(max_lines=10).classes('w-full')\n", "logger.addHandler(LogElementHandler(log))\n", "ui.button('Log time', on_click=lambda: logger.warning(datetime.now().strftime('%X.%f')[:-5]))\n", "\n", "# ui.run()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "py311", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.7" } }, "nbformat": 4, "nbformat_minor": 2 }