✨ New plugin timings logging feature

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
This commit is contained in:
Gina Häußge committed 2020-09-30 13:58:47 +02:00
1 parent 24204efab6
commit 22ce8e4c24
15 files changed
+153 -20

No files matched your search

+30
View File
@@ -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"
},
+2
View File
@@ -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__))
+12 -3
View File
@@ -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)
+18 -2
View File
@@ -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):
+5 -1
View File
@@ -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)
]
@@ -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 = "<p>"
+ gettext("You currently have <code>serial.log</code> 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 <code>%(logfile)s</code> enabled. Please remember to turn it off " +
"again once your are done debugging whatever issue prompted you to turn it on."), {logfile: logfile})
+ "</p><p>"
+ 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.")
+ "</p>";
@@ -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"]
});
});
@@ -0,0 +1,3 @@
<a href="https://faq.octoprint.org/plugintimings-log" target="_blank" title="{{ _('plugintimings.log is enabled') }}" rel="noopener noreferrer" data-bind="visible: pluginTimingsLogEnabled(), popover: { placement: 'bottom', title: '{{ _('<code>plugintimings.log</code> is enabled')|esq }}', html: true, content: pluginTimingsLogPopoverContent, trigger: 'hover' }" style="display: none">
<i class="fa fa-file-text"></i>
</a>
@@ -1,3 +1,3 @@
<a href="https://faq.octoprint.org/serial-log" target="_blank" title="{{ _('serial.log is enabled') }}" rel="noopener noreferrer" data-bind="visible: serialLogEnabled(), popover: { placement: 'bottom', title: '{{ _('<code>serial.log</code> is enabled')|esq }}', html: true, content: popoverContent, trigger: 'hover' }" style="display: none">
<a href="https://faq.octoprint.org/serial-log" target="_blank" title="{{ _('serial.log is enabled') }}" rel="noopener noreferrer" data-bind="visible: serialLogEnabled(), popover: { placement: 'bottom', title: '{{ _('<code>serial.log</code> is enabled')|esq }}', html: true, content: serialLogPopoverContent, trigger: 'hover' }" style="display: none">
<i class="fa fa-file-text"></i>
</a>
+1 -1
View File
@@ -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")
+4
View File
@@ -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()
+15
View File
@@ -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
+3 -2
View File
@@ -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."""
@@ -16,4 +16,8 @@
{% include "snippets/settings/server/serverPluginBlacklistDescription.jinja2" %}
{% include "snippets/settings/server/serverPluginBlacklist.jinja2" %}
<h3>{{ _('Debug options') }}</h3>
{% include "snippets/settings/server/serverPluginTimings.jinja2" %}
</form>
@@ -0,0 +1,8 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.devel.pluginTimings" id="settings-develPluginTimings"> {{ _('Enable <code>plugintimings.log</code>') }} <label class="label label-important">{{ _("Warning") }}</label>
<span class="help-block">{{ _('While this can negatively impact performance, a <code>plugintimings.log</code> can be incredibly useful for debugging any performance issues observed outside of safe mode.') }}</span>
</label>
</div>
</div>
+25 -4
View File
@@ -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