From 22ce8e4c246b260ffa89b7274be93db8404caa7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 30 Sep 2020 13:58:47 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20New=20plugin=20timings=20logging=20?= =?UTF-8?q?feature?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If enabled (via Settings > Server > Debug options) this will write two new files to the logging dir, plugintimings.log and plugintimings.csv, which contain timing information for each and every hook or implementation call on plugins registered with OctoPrint. This should be helpful to debug any kind of performance issues caused by third party plugins. It should also be a valuable tool to debug performance issues with bundled plugins. As requested in #1241 --- src/octoprint/__init__.py | 30 +++++++++++++++++++ src/octoprint/cli/server.py | 2 ++ src/octoprint/logging/handlers.py | 15 ++++++++-- src/octoprint/plugin/core.py | 20 +++++++++++-- src/octoprint/plugins/logging/__init__.py | 6 +++- .../plugins/logging/static/js/logging.js | 28 +++++++++++++---- .../logging_navbar_plugintimingslog.jinja2 | 3 ++ ...jinja2 => logging_navbar_seriallog.jinja2} | 2 +- src/octoprint/printer/standard.py | 2 +- src/octoprint/server/__init__.py | 4 +++ src/octoprint/server/api/settings.py | 15 ++++++++++ src/octoprint/settings.py | 5 ++-- .../templates/dialogs/settings/server.jinja2 | 4 +++ .../server/serverPluginTimings.jinja2 | 8 +++++ src/octoprint/util/__init__.py | 29 +++++++++++++++--- 15 files changed, 153 insertions(+), 20 deletions(-) create mode 100644 src/octoprint/plugins/logging/templates/logging_navbar_plugintimingslog.jinja2 rename src/octoprint/plugins/logging/templates/{logging_navbar.jinja2 => logging_navbar_seriallog.jinja2} (75%) create mode 100644 src/octoprint/templates/snippets/settings/server/serverPluginTimings.jinja2 diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 0196952f7..ac9262bb9 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -243,6 +243,12 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con }, "serial": { "format": "%(asctime)s - %(message)s" + }, + "timings": { + "format": "%(asctime)s - %(message)s" + }, + "timingscsv": { + "format": "%(asctime)s;%(func)s;%(timing)f" } }, "handlers": { @@ -267,6 +273,22 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con "backupCount": 3, "filename": os.path.join(settings.getBaseFolder("logs"), "serial.log"), "delay": True + }, + "pluginTimingsFile": { + "class": "octoprint.logging.handlers.PluginTimingsLogHandler", + "level": "DEBUG", + "formatter": "timings", + "backupCount": 3, + "filename": os.path.join(settings.getBaseFolder("logs"), "plugintimings.log"), + "delay": True + }, + "pluginTimingsCsvFile": { + "class": "octoprint.logging.handlers.PluginTimingsLogHandler", + "level": "DEBUG", + "formatter": "timingscsv", + "backupCount": 3, + "filename": os.path.join(settings.getBaseFolder("logs"), "plugintimings.csv"), + "delay": True } }, "loggers": { @@ -275,6 +297,14 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con "handlers": ["serialFile"], "propagate": False }, + "PLUGIN_TIMINGS": { + "level": "INFO", + "handlers": ["pluginTimingsFile", "pluginTimingsCsvFile"], + "propagate": False + }, + "PLUGIN_TIMINGS.octoprint.plugin": { + "level": "INFO" + }, "octoprint": { "level": "INFO" }, diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 5a28741a9..6517b70ce 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -20,8 +20,10 @@ def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logg def log_startup(recorder=None, safe_mode=None, **kwargs): from octoprint.logging import get_divider_line + from octoprint.logging.handlers import PluginTimingsLogHandler logger = logging.getLogger("octoprint.startup") + PluginTimingsLogHandler.arm_rollover() logger.info(get_divider_line("*")) logger.info("Starting OctoPrint {}".format(__display_version__)) diff --git a/src/octoprint/logging/handlers.py b/src/octoprint/logging/handlers.py index bf7c47992..30a9e8e6e 100644 --- a/src/octoprint/logging/handlers.py +++ b/src/octoprint/logging/handlers.py @@ -69,19 +69,19 @@ class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler): pass -class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler): +class TriggeredRolloverLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler): do_rollover = False suffix_template = "%Y-%m-%d_%H-%M-%S" file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$") @classmethod - def on_open_connection(cls): + def arm_rollover(cls): cls.do_rollover = True def __init__(self, *args, **kwargs): kwargs["encoding"] = kwargs.get("encoding", "utf-8") - super(SerialLogHandler, self).__init__(*args, **kwargs) + super(TriggeredRolloverLogHandler, self).__init__(*args, **kwargs) self.cleanupFiles() def shouldRollover(self, record): @@ -132,6 +132,15 @@ class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandle if not self.delay: self.stream = self._open() + +class SerialLogHandler(TriggeredRolloverLogHandler): + pass + + +class PluginTimingsLogHandler(TriggeredRolloverLogHandler): + pass + + class RecordingLogHandler(logging.Handler): def __init__(self, target=None, *args, **kwargs): super(RecordingLogHandler, self).__init__(*args, **kwargs) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 756ddcab8..f49be0257 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -38,7 +38,7 @@ import pkginfo from past.builtins import unicode -from octoprint.util import to_unicode, sv +from octoprint.util import to_unicode, sv, time_this from octoprint.util.version import is_python_compatible, get_python_version_string try: @@ -727,6 +727,9 @@ class PluginManager(object): It is able to discover plugins both through possible file system locations as well as customizable entry points. """ + plugin_timings_logtarget = "PLUGIN_TIMINGS" + plugin_timings_message = "{func} - {timing:05.2f}ms" + def __init__(self, plugin_folders, plugin_bases, plugin_entry_points, logging_prefix=None, plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_considered_bundled=None, plugin_validators=None, @@ -1365,8 +1368,18 @@ class PluginManager(object): mixins = self.mixins_matching_bases(plugin.implementation.__class__, *self.plugin_bases) for mixin in mixins: self.plugin_implementations_by_type[mixin].append((name, plugin.implementation)) + if not getattr(plugin.implementation, "__timing_wrapped", False): + for method in filter(lambda a: not a.startswith("_") and callable(getattr(mixin, a)), dir(mixin)): + # wrap method with time_this + setattr(plugin.implementation, + method, + time_this(getattr(plugin.implementation, method), + logtarget=self.plugin_timings_logtarget, + expand_logtarget=True, + message=self.plugin_timings_message)) self.plugin_implementations[name] = plugin.implementation + setattr(plugin.implementation, "__timing_wrapped", True) def _deactivate_plugin(self, name, plugin): for hook, definition in plugin.hooks.items(): @@ -1697,7 +1710,10 @@ class PluginManager(object): result = OrderedDict() for h in self.plugin_hooks[hook]: - result[h[0]] = h[1] + result[h[0]] = time_this(h[1], + logtarget=self.plugin_timings_logtarget, + expand_logtarget=True, + message=self.plugin_timings_message) return result def get_implementations(self, *types, **kwargs): diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index d0cc01e69..b12e818f9 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -52,9 +52,11 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, loggers = self._get_available_loggers() levels = self._get_logging_levels() serial_log_enabled = self._settings.global_get_boolean(["serial", "log"]) + plugintimings_log_enabled = self._settings.global_get_boolean(["devel", "pluginTimings"]) return jsonify(logs=dict(files=files, free=free, total=total), setup=dict(loggers=loggers, levels=levels), - serial_log=dict(enabled=serial_log_enabled)) + serial_log=dict(enabled=serial_log_enabled), + plugintimings_log=dict(enabled=plugintimings_log_enabled)) @octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"]) @no_firstrun_access @@ -213,6 +215,8 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, def get_template_configs(self): return [ + dict(type="navbar", template="logging_navbar_seriallog.jinja2", suffix="_seriallog"), + dict(type="navbar", template="logging_navbar_plugintimingslog.jinja2", suffix="_plugintimingslog"), dict(type="settings", custom_bindings=True) ] diff --git a/src/octoprint/plugins/logging/static/js/logging.js b/src/octoprint/plugins/logging/static/js/logging.js index ff37477f7..910b6c1d5 100644 --- a/src/octoprint/plugins/logging/static/js/logging.js +++ b/src/octoprint/plugins/logging/static/js/logging.js @@ -11,6 +11,7 @@ $(function() { self.configuredLoggers = ko.observableArray(); self.configuredLoggersChanged = false; self.serialLogEnabled = ko.observable(); + self.pluginTimingsLogEnabled = ko.observable(); self.freeSpace = ko.observable(undefined); self.totalSpace = ko.observable(undefined); @@ -70,6 +71,7 @@ $(function() { self.fromLogsResponse(response.logs); self.fromSetupResponse(response.setup); self.fromSerialLogResponse(response.serial_log); + self.fromPluginTimingsLogResponse(response.plugintimings_log); }; self.fromLogsResponse = function(response) { @@ -112,16 +114,30 @@ $(function() { self.serialLogEnabled(response.enabled); }; - self.popoverContent = function() { + self.fromPluginTimingsLogResponse = function(response) { + if (!response) return; + + self.pluginTimingsLogEnabled(response.enabled); + }; + + self.serialLogPopoverContent = function() { + return self.popoverContent("serial.log"); + }; + + self.pluginTimingsLogPopoverContent = function() { + return self.popoverContent("plugintimings.log"); + }; + + self.popoverContent = function(logfile) { var free = self.freeSpace(); var total = self.totalSpace(); var content = "

" - + gettext("You currently have serial.log enabled. Please remember to turn it off " + - "again once your are done debugging whatever issue prompted you to turn it on.") + + _.sprintf(gettext("You currently have %(logfile)s enabled. Please remember to turn it off " + + "again once your are done debugging whatever issue prompted you to turn it on."), {logfile: logfile}) + "

" + gettext("It can negatively impact print performance and also take up a lot of storage space " + - "depending on how long you stay connected to your printer and thus should only be used for " + + "depending on how long you keep it enabled and thus should only be used for " + "debugging.") + "

"; @@ -133,7 +149,7 @@ $(function() { } return content; - }; + } self.configuredLoggersHasChanged = function () { self.configuredLoggersChanged = true; @@ -279,6 +295,6 @@ $(function() { construct: LoggingViewModel, additionalNames: ["logsViewModel"], dependencies: ["loginStateViewModel", "accessViewModel"], - elements: ["#settings_plugin_logging", "#navbar_plugin_logging"] + elements: ["#settings_plugin_logging", "#navbar_plugin_logging_seriallog", "#navbar_plugin_logging_plugintimingslog"] }); }); diff --git a/src/octoprint/plugins/logging/templates/logging_navbar_plugintimingslog.jinja2 b/src/octoprint/plugins/logging/templates/logging_navbar_plugintimingslog.jinja2 new file mode 100644 index 000000000..3b3d27f43 --- /dev/null +++ b/src/octoprint/plugins/logging/templates/logging_navbar_plugintimingslog.jinja2 @@ -0,0 +1,3 @@ + + + diff --git a/src/octoprint/plugins/logging/templates/logging_navbar.jinja2 b/src/octoprint/plugins/logging/templates/logging_navbar_seriallog.jinja2 similarity index 75% rename from src/octoprint/plugins/logging/templates/logging_navbar.jinja2 rename to src/octoprint/plugins/logging/templates/logging_navbar_seriallog.jinja2 index f03a75d09..e4fdbd111 100644 --- a/src/octoprint/plugins/logging/templates/logging_navbar.jinja2 +++ b/src/octoprint/plugins/logging/templates/logging_navbar_seriallog.jinja2 @@ -1,3 +1,3 @@ - + diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index a94d3eb24..050692e48 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -285,7 +285,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._printerProfileManager.select(profile) from octoprint.logging.handlers import SerialLogHandler - SerialLogHandler.on_open_connection() + SerialLogHandler.arm_rollover() if not logging.getLogger("SERIAL").isEnabledFor(logging.DEBUG): # if serial.log is not enabled, log a line to explain that to reduce "serial.log is empty" in tickets... logging.getLogger("SERIAL").info("serial.log is currently not enabled, you can enable it via Settings > Serial Connection > Log communication to serial.log") diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 659e434d1..a8c19e827 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -302,6 +302,10 @@ class Server(object): # enable debug logging to serial.log logging.getLogger("SERIAL").setLevel(logging.DEBUG) + if self._settings.getBoolean(["devel", "pluginTimings"]): + # enable plugin timings log + logging.getLogger("PLUGIN_TIMINGS").setLevel(logging.DEBUG) + # start the intermediary server self._start_intermediary_server() diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index b07d1e7d5..fd4ebc533 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -253,6 +253,9 @@ def getSettings(): "ttl": int(s.getInt(["server", "pluginBlacklist", "ttl"]) / 60) }, "allowFraming": s.getBoolean(["server", "allowFraming"]) + }, + "devel": { + "pluginTimings": s.getBoolean(["devel", "pluginTimings"]) } } @@ -578,6 +581,18 @@ def _saveSettings(data): if "allowFraming" in data["server"]: s.setBoolean(["server", "allowFraming"], data["server"]["allowFraming"]) + if "devel" in data: + oldLog = s.getBoolean(["devel", "pluginTimings"]) + if "pluginTimings" in data["devel"]: s.setBoolean(["devel", "pluginTimings"], data["devel"]["pluginTimings"]) + if oldLog and not s.getBoolean(["devel", "pluginTimings"]): + # disable plugin timing logging to plugintimings.log + logging.getLogger("PLUGIN_TIMINGS").debug("Disabling plugin timings logging") + logging.getLogger("PLUGIN_TIMINGS").setLevel(logging.INFO) + elif not oldLog and s.getBoolean(["devel", "pluginTimings"]): + # enable plugin timing logging to plugintimings.log + logging.getLogger("PLUGIN_TIMINGS").setLevel(logging.DEBUG) + logging.getLogger("PLUGIN_TIMINGS").debug("Enabling plugin timings logging") + if "plugins" in data: for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin): plugin_id = plugin._identifier diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index d4a3c4e8e..50898fbec 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -319,7 +319,7 @@ default_settings = { "closeModalsWithClick": True, "components": { "order": { - "navbar": ["settings", "systemmenu", "plugin_announcements", "plugin_logging", "plugin_pi_support", "login"], + "navbar": ["settings", "systemmenu", "plugin_announcements", "plugin_logging_seriallog", "plugin_logging_plugintimingslog", "plugin_pi_support", "login"], "sidebar": ["plugin_firmware_check", "connection", "state", "files"], "tab": ["temperature", "control", "plugin_gcodeviewer", "terminal", "timelapse"], "settings": [ @@ -421,7 +421,8 @@ default_settings = { }, "useFrozenDictForPrinterState": True, "showLoadingAnimation": True, - "sockJsConnectTimeout": 30 + "sockJsConnectTimeout": 30, + "pluginTimings": False } } """The default settings of the core application.""" diff --git a/src/octoprint/templates/dialogs/settings/server.jinja2 b/src/octoprint/templates/dialogs/settings/server.jinja2 index 41a0884af..addf96111 100644 --- a/src/octoprint/templates/dialogs/settings/server.jinja2 +++ b/src/octoprint/templates/dialogs/settings/server.jinja2 @@ -16,4 +16,8 @@ {% include "snippets/settings/server/serverPluginBlacklistDescription.jinja2" %} {% include "snippets/settings/server/serverPluginBlacklist.jinja2" %} + +

{{ _('Debug options') }}

+ + {% include "snippets/settings/server/serverPluginTimings.jinja2" %} diff --git a/src/octoprint/templates/snippets/settings/server/serverPluginTimings.jinja2 b/src/octoprint/templates/snippets/settings/server/serverPluginTimings.jinja2 new file mode 100644 index 000000000..afa3ae465 --- /dev/null +++ b/src/octoprint/templates/snippets/settings/server/serverPluginTimings.jinja2 @@ -0,0 +1,8 @@ +
+
+ +
+
diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index f1b82e4ef..fcfaf7e62 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -25,6 +25,7 @@ import contextlib import collections import frozendict import copy +import time from typing import Union @@ -1723,17 +1724,37 @@ def count(gen): n += 1 return n +def fqfn(f): + if hasattr(f, "__self__"): + # bound method + return "{}.{}.{}".format(f.__self__.__class__.__module__, + f.__self__.__class__.__name__, + f.__name__) + else: + return "{}.{}".format(f.__module__, + f.__name__) -def timing(f): + +def time_this(f, logtarget="octoprint.util.timings", expand_logtarget=False, message="{func} took {timing:.2f}ms"): @wraps(f) def decorator(*args, **kwargs): start = monotonic_time() try: return f(*args, **kwargs) finally: - end = monotonic_time() - logging.getLogger("octoprint.util.timing").debug("func:{} took {:0.2f}s".format(f.__name__, - end - start)) + timing = (monotonic_time() - start) * 1000.0 + func = fqfn(f) + + l = logtarget + if expand_logtarget: + l += "." + func + + logger = logging.getLogger(l) + if logger.isEnabledFor(logging.DEBUG): + data = {"func": func, "timing": timing} + logger.debug(message.format(**data), + extra=data) + return decorator