Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Papertrail JSON formatter (with addStyle fix)
// ==UserScript==
// @name Papertrail JSON formatter
// @namespace https://papertrailapp.com/
// @version 0.1
// @description Format and colorize JSON log messages in Papertrail
// @match https://papertrailapp.com/*events*
// @copyright 2014+, Papertrail (http://wiki.creativecommons.org/Public_domain)
// @grant GM_addStyle
// ==/UserScript==
GM_addStyle(".string { color: #6c71c4; } .number { color: #2aa198; } .boolean { color: #859900; } .null { color: #586e75; } .key { color: #d33682; }");
function syntaxHighlight(json) {
json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
$('ul#event_list').on('papertrail:loaded', function() {
$('span.message').each(function(m) {
console.log("Parsing: " + $(this).text());
if ($(this).text().substring(0, 1) != '{') {
return;
}
try {
var formattedString = JSON.stringify(jQuery.parseJSON($(this).text()), undefined, 4);
} catch(err) {
return;
}
console.log(formattedString);
formattedString = syntaxHighlight(formattedString);
formattedString = formattedString.replace(/^{+/g, '').replace(/}+$/g, '');
formatted = document.createElement('pre');
formatted = formattedString.replace(/\n /mg, "\n ");
console.log(formattedString);
formatted.innerHTML = formattedString;
$(this).html(formatted);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.