Logging: extract log managment into bundled plugin

This commit is contained in:
Shawn Bruce authored and Gina Häußge committed 2018-02-07 14:11:49 +01:00
1 parent ec12bd7cd4
commit 986591aed4
13 files changed
+412 -219

No files matched your search

+170
View File
@@ -0,0 +1,170 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__author__ = ""
__license__ = ''
__copyright__ = ""
import octoprint.plugin
from octoprint.settings import settings
from octoprint.server import NO_CONTENT, admin_permission
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
from flask import request, jsonify, url_for, make_response
from werkzeug.utils import secure_filename
import yaml
import json
import os
try:
from os import scandir
except ImportError:
from scandir import scandir
class LogsPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SimpleApiPlugin):
@octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"])
@restricted_access
@admin_permission.require(403)
def getLogFiles(self):
import psutil
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
files = self._getLogFiles()
return jsonify(files=files, free=usage.free, total=usage.total)
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["GET"])
@restricted_access
@admin_permission.require(403)
def downloadLog(self, filename):
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["DELETE"])
@restricted_access
@admin_permission.require(403)
def deleteLog(self, filename):
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
if not os.path.exists(secure):
return make_response("File not found: %s" % filename, 404)
os.remove(secure)
return NO_CONTENT
def _getLogFiles(self):
files = []
basedir = settings().getBaseFolder("logs")
for entry in scandir(basedir):
files.append({
"name": entry.name,
"date": int(entry.stat().st_mtime),
"size": entry.stat().st_size,
"refs": {
"resource": url_for(".downloadLog", filename=entry.name, _external=True),
"download": url_for("index", _external=True) + "downloads/logs/" + entry.name
}
})
return files
def get_available_loggers(self):
return self._logger.manager.loggerDict.keys()
def get_logging_config(self):
logging_file = os.path.join(self._settings.getBaseFolder("base"), "logging.yaml")
config_from_file = {}
if os.path.exists(logging_file) and os.path.isfile(logging_file):
import yaml
with open(logging_file, "r") as f:
config_from_file = yaml.safe_load(f)
if config_from_file is not None and isinstance(config_from_file, dict):
return config_from_file
else:
return dict()
def set_logging_config(self, new_config):
import logging
logging_file = os.path.join(self._settings.getBaseFolder("base"), "logging.yaml")
config = self.get_logging_config();
# clear all configured logging levels
if config.has_key("loggers"):
for component in config["loggers"]:
try:
del config["loggers"][component]["level"]
self._logger.manager.loggerDict[component].setLevel(logging.INFO)
except:
pass
else:
config["loggers"] = dict()
# update all logging levels
for logger in new_config:
if not config["loggers"].has_key(logger["component"]):
config["loggers"][logger["component"]] = dict()
config["loggers"][logger["component"]]["level"] = logger["level"]
# save
with octoprint.util.atomic_write(logging_file, "wb", max_permissions=0o666) as f:
yaml.safe_dump(config, f, default_flow_style=False, indent=" ", allow_unicode=True)
# set runtime logging levels now
for logger in new_config:
level = logging.getLevelName(logger["level"])
self._logger.info("Setting logger {} level to {}".format(logger["component"], logger["level"]))
self._logger.manager.loggerDict[logger["component"]].setLevel(level)
def get_api_commands(self):
return dict(
getAvailableLoggers=[],
getLoggingConfig=[],
setLoggingConfig=["config"]
)
def on_api_command(self, command, data):
if not admin_permission.can():
return make_response("Insufficient rights", 403)
if command == 'getAvailableLoggers':
return jsonify(result=self.get_available_loggers())
elif command == 'getLoggingConfig':
return jsonify(result=self.get_logging_config())
elif command == 'setLoggingConfig':
config = json.loads(data["config"])
return self.set_logging_config(config)
def get_template_configs(self):
return [
dict(type="settings", custom_bindings=True)
]
def get_assets(self):
return dict(js=["js/logs.js"])
__plugin_name__ = "Logs"
__plugin_author__ = ""
__plugin_description__ = "Provides access to OctoPrint Logs."
__plugin_license__ = ""
#__plugin_implementation__ = LogsPlugin()
# Required for regular plugin
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = LogsPlugin()
@@ -0,0 +1,148 @@
$(function() {
function LogsViewModel(parameters) {
var self = this;
var logsURL = "plugin/logs/logs"
self.loginState = parameters[0];
self.availableLoggers = ko.observableArray();
self.availableLoggersName = ko.observable();
self.availableLoggersLevel = ko.observable();
self.configuredLoggers = ko.observableArray();
self.configuredLoggersChanged = false;
self.availableLoggersSorted = ko.computed(function() {
return _.sortBy(self.availableLoggers());
});
self.configuredLoggersSorted = ko.computed(function() {
return _.sortBy(self.configuredLoggers(), function (o) {
o.level();
return o.component;
});
});
// initialize list helper
self.listHelper = new ItemListHelper(
"logFiles",
{
"name": function(a, b) {
// sorts ascending
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
return 0;
},
"modification": function(a, b) {
// sorts descending
if (a["date"] > b["date"]) return -1;
if (a["date"] < b["date"]) return 1;
return 0;
},
"size": function(a, b) {
// sorts descending
if (a["size"] > b["size"]) return -1;
if (a["size"] < b["size"]) return 1;
return 0;
}
},
{
},
"name",
[],
[],
CONFIG_LOGFILESPERPAGE
);
self.requestData = function() {
OctoPrint.get(logsURL)
.done(self.fromResponse);
OctoPrint.simpleApiCommand("logs", "getLoggingConfig")
.done(self.fromGetLoggingConfigResponse);
OctoPrint.simpleApiCommand("logs", "getAvailableLoggers")
.done(self.fromGetAvailableLoggersResponse);
};
self.fromResponse = function(response) {
var files = response.files;
if (files === undefined)
return;
self.listHelper.updateItems(files);
};
self.fromGetLoggingConfigResponse = function(data) {
self.configuredLoggers([]);
$.each(data.result.loggers, function(component, options) {
if (options.level !== undefined) {
self.configuredLoggers.push({component: component, level: ko.observable(options.level)});
}
});
self.configuredLoggersChanged = false;
};
self.fromGetAvailableLoggersResponse = function(data) {
self.availableLoggers([]);
$.each(data.result, function(key, component) {
if (component.toLowerCase().indexOf("octoprint") >= 0) {
self.availableLoggers.push(component);
}
});
$.each(self.configuredLoggers(), function(key, logger) {
self.availableLoggers.remove(logger.component);
});
};
self.configuredLoggersHasChanged = function () {
self.configuredLoggersChanged = true;
};
self.addLogger = function() {
component = self.availableLoggersName();
level = self.availableLoggersLevel();
self.configuredLoggers.push({component: component, level: ko.observable(level)});
self.availableLoggers.remove(component);
self.configuredLoggersHasChanged();
};
self.removeLogger = function(logger) {
self.configuredLoggers.remove(logger);
self.availableLoggers.push(logger.component);
self.configuredLoggersHasChanged();
};
self.removeFile = function(filename) {
OctoPrint.delete(logsURL + "/" + filename)
.done(self.requestData);
};
self.onSettingsShown = function() {
self.requestData();
};
self.onSettingsBeforeSave = function () {
if ( self.configuredLoggersChanged ) {
console.log("ConfiguredLoggers has changed. Saving!");
OctoPrint.simpleApiCommand("logs", "setLoggingConfig", {'config': ko.toJSON(self.configuredLoggers)});
} else {
console.log("ConfiguredLoggers has not changed. Not saving.");
}
};
}
OCTOPRINT_VIEWMODELS.push([
LogsViewModel,
["loginStateViewModel"],
"#settings_plugin_logs"
]);
});
@@ -0,0 +1,91 @@
<h3>{{ _('Logs') }}</h3>
<div class="pull-right">
<small>
{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('modification'); }">{{ _('Modification date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a>
</small>
</div>
<table class="table table-striped table-hover table-condensed table-hover" id="log_files">
<thead>
<tr>
<th class="settings_logs_name">{{ _('Name') }}</th>
<th class="settings_logs_size">{{ _('Size') }}</th>
<th class="settings_logs_date">{{ _('Date') }}</th>
<th class="settings_logs_action">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: listHelper.paginatedItems">
<tr data-bind="attr: {title: name}">
<td class="settings_logs_name" data-bind="text: name"></td>
<td class="settings_logs_size" data-bind="text: formatSize(size)"></td>
<td class="settings_logs_date" data-bind="text: formatDate(date)"></td>
<td class="settings_logs_action">
<a href="#" class="icon-trash" data-bind="click: function() { if ($root.loginState.isUser()) { $parent.removeFile($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser()}"></a>&nbsp;|&nbsp;<a href="#" class="icon-download" data-bind="attr: {href: refs.download}"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: listHelper.currentPage() === 0}">
<a href="#" data-bind="click: listHelper.prevPage">«</a>
</li>
</ul>
<ul data-bind="foreach: listHelper.pages">
<li data-bind="css: { active: $data.number === $root.listHelper.currentPage(), disabled: $data.number === -1 }">
<a href="#" data-bind="text: $data.text, click: function() { $root.listHelper.changePage($data.number); }"></a>
</li>
</ul>
<ul>
<li data-bind="css: {disabled: listHelper.currentPage() === listHelper.lastPage()}">
<a href="#" data-bind="click: listHelper.nextPage">»</a>
</li>
</ul>
</div>
<h3>Logging Levels</h3>
<form class="form-horizontal">
<div class="row-fluid">
<div class="span8"><h5>Name</h5></div>
<div class="span2"><h5>Level</h5></div>
</div>
<div data-bind="foreach: configuredLoggersSorted">
<div class="row-fluid" style="margin-bottom: 5px">
<div class="span8">
<span data-bind="text: component"></span>
</div>
<div class="span3">
<select data-bind="value: level, event: { change: $parent.configuredLoggersHasChanged }" class="input-medium">
<option value="DEBUG">DEBUG</option>
<option value="INFO">INFO</option>
<option value="WARNING">WARNING</option>
<option value="ERROR">ERROR</option>
<option value="CRITICAL">CRITICAL</option>
</select>
</div>
<div class="span1">
<a title="Remove" class="btn btn-danger" data-bind="click: $parent.removeLogger"><i class="icon-trash"></i></a>
</div>
</div>
</div>
<div>
<div class="row-fluid" style="margin-bottom: 5px">
<div class="span8">
<select class="input-block-level" data-bind="options: availableLoggersSorted, value: availableLoggersName"></select>
</div>
<div class="span3">
<select class="input-medium" data-bind="value: availableLoggersLevel">
<option value="DEBUG">DEBUG</option>
<option value="INFO">INFO</option>
<option value="WARNING">WARNING</option>
<option value="ERROR">ERROR</option>
<option value="CRITICAL">CRITICAL</option>
</select>
</div>
<div class="span1">
<a title="Add" class="btn btn-primary" data-bind="click: $root.addLogger"><i class="icon-plus"></i></a>
</div>
</div>
</div>
</form>
-1
View File
@@ -1223,7 +1223,6 @@ class Server(object):
"js/app/client/files.js",
"js/app/client/job.js",
"js/app/client/languages.js",
"js/app/client/logs.js",
"js/app/client/printer.js",
"js/app/client/printerprofiles.js",
"js/app/client/settings.js",
-1
View File
@@ -34,7 +34,6 @@ from . import files as api_files
from . import settings as api_settings
from . import timelapse as api_timelapse
from . import users as api_users
from . import log as api_logs
from . import slicing as api_slicing
from . import printer_profiles as api_printer_profiles
from . import languages as api_languages
-72
View File
@@ -1,72 +0,0 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__author__ = "Marc Hannappel Salandora"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
try:
from os import scandir
except ImportError:
from scandir import scandir
from flask import request, jsonify, url_for, make_response
from werkzeug.utils import secure_filename
from octoprint.settings import settings
from octoprint.server import NO_CONTENT, admin_permission
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
from octoprint.server.api import api
@api.route("/logs", methods=["GET"])
@restricted_access
@admin_permission.require(403)
def getLogFiles():
import psutil
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
files = _getLogFiles()
return jsonify(files=files, free=usage.free, total=usage.total)
@api.route("/logs/<path:filename>", methods=["GET"])
@restricted_access
@admin_permission.require(403)
def downloadLog(filename):
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
@api.route("/logs/<path:filename>", methods=["DELETE"])
@restricted_access
@admin_permission.require(403)
def deleteLog(filename):
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
if not os.path.exists(secure):
return make_response("File not found: %s" % filename, 404)
os.remove(secure)
return NO_CONTENT
def _getLogFiles():
files = []
basedir = settings().getBaseFolder("logs")
for entry in scandir(basedir):
files.append({
"name": entry.name,
"date": int(entry.stat().st_mtime),
"size": entry.stat().st_size,
"refs": {
"resource": url_for(".downloadLog", filename=entry.name, _external=True),
"download": url_for("index", _external=True) + "downloads/logs/" + entry.name
}
})
return files
-1
View File
@@ -1324,7 +1324,6 @@ def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
'js/app/viewmodels/terminal.js',
'js/app/viewmodels/timelapse.js',
'js/app/viewmodels/users.js',
'js/app/viewmodels/log.js',
'js/app/viewmodels/usersettings.js',
'js/app/viewmodels/wizard.js',
'js/app/viewmodels/about.js'
-1
View File
@@ -573,7 +573,6 @@ def _process_templates():
accesscontrol=(gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False)),
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
server=(gettext("Server"), dict(template="dialogs/settings/server.jinja2", _div="settings_server", custom_bindings=False)),
)
+1 -1
View File
@@ -273,7 +273,7 @@ default_settings = {
"settings": [
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
"section_features", "features", "webcam", "accesscontrol", "gcodevisualizer", "api",
"section_octoprint", "server", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate", "plugin_announcements"
"section_octoprint", "server", "folders", "appearance", "plugin_logs", "plugin_pluginmanager", "plugin_softwareupdate", "plugin_announcements"
],
"usersettings": ["access", "interface"],
"wizard": ["access"],
@@ -1,30 +0,0 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var url = "api/logs";
var OctoPrintLogsClient = function(base) {
this.base = base;
};
OctoPrintLogsClient.prototype.list = function(opts) {
return this.base.get(url, opts);
};
OctoPrintLogsClient.prototype.delete = function(file, opts) {
var fileUrl = url + "/" + file;
return this.base.delete(fileUrl, opts);
};
OctoPrintLogsClient.prototype.download = function(file, opts) {
var fileUrl = url + "/" + file;
return this.base.download(fileUrl, opts);
};
OctoPrintClient.registerComponent("logs", OctoPrintLogsClient);
return OctoPrintLogsClient;
});
@@ -1,66 +0,0 @@
$(function() {
function LogViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
// initialize list helper
self.listHelper = new ItemListHelper(
"logFiles",
{
"name": function(a, b) {
// sorts ascending
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
return 0;
},
"modification": function(a, b) {
// sorts descending
if (a["date"] > b["date"]) return -1;
if (a["date"] < b["date"]) return 1;
return 0;
},
"size": function(a, b) {
// sorts descending
if (a["size"] > b["size"]) return -1;
if (a["size"] < b["size"]) return 1;
return 0;
}
},
{
},
"name",
[],
[],
CONFIG_LOGFILESPERPAGE
);
self.requestData = function() {
OctoPrint.logs.list()
.done(self.fromResponse);
};
self.fromResponse = function(response) {
var files = response.files;
if (files === undefined)
return;
self.listHelper.updateItems(files);
};
self.removeFile = function(filename) {
OctoPrint.logs.delete(filename)
.done(self.requestData);
};
self.onSettingsShown = function() {
self.requestData();
};
}
OCTOPRINT_VIEWMODELS.push({
construct: LogViewModel,
dependencies: ["loginStateViewModel"],
elements: ["#logs"]
});
});
+2
View File
@@ -364,6 +364,7 @@ table {
.actioncol;
}
/*
// log files
&.settings_logs_name {
text-overflow: ellipsis;
@@ -384,6 +385,7 @@ table {
width: 70px;
.actioncol;
}
*/
// Printer profiles
&.settings_printerProfiles_profiles_name {
@@ -1,46 +0,0 @@
<div id="logs">
<h1>{{ _('Logs') }}</h1>
<div class="pull-right">
<small>
{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('modification'); }">{{ _('Modification date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a>
</small>
</div>
<table class="table table-striped table-hover table-condensed table-hover" id="log_files">
<thead>
<tr>
<th class="settings_logs_name">{{ _('Name') }}</th>
<th class="settings_logs_size">{{ _('Size') }}</th>
<th class="settings_logs_date">{{ _('Date') }}</th>
<th class="settings_logs_action">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: listHelper.paginatedItems">
<tr data-bind="attr: {title: name}">
<td class="settings_logs_name" data-bind="text: name"></td>
<td class="settings_logs_size" data-bind="text: formatSize(size)"></td>
<td class="settings_logs_date" data-bind="text: formatDate(date)"></td>
<td class="settings_logs_action">
<a href="#" class="fa fa-trash-o" data-bind="click: function() { if ($root.loginState.isUser()) { $parent.removeFile($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser()}"></a>&nbsp;|&nbsp;<a href="#" class="fa fa-download" data-bind="attr: {href: refs.download}"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: listHelper.currentPage() === 0}">
<a href="#" data-bind="click: listHelper.prevPage">«</a>
</li>
</ul>
<ul data-bind="foreach: listHelper.pages">
<li data-bind="css: { active: $data.number === $root.listHelper.currentPage(), disabled: $data.number === -1 }">
<a href="#" data-bind="text: $data.text, click: function() { $root.listHelper.changePage($data.number); }"></a>
</li>
</ul>
<ul>
<li data-bind="css: {disabled: listHelper.currentPage() === listHelper.lastPage()}">
<a href="#" data-bind="click: listHelper.nextPage">»</a>
</li>
</ul>
</div>
</div>