Created
January 23, 2020 16:20
-
-
Save megastef/6002f54aeb52158c1e2594d9ecc70d3e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sematextLogger (url, token) { | |
var sematextUrl = url || `https://logsene-receiver.sematext.com/${token}/_bulk/` | |
var logBuffer = '' | |
let consoleLog = console.log | |
let lineCount = 0 | |
const sessionId = /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false | |
let consoleFunctions = { | |
debug: console.debug, | |
error: console.error, | |
warn: console.warn, | |
log: console.log, | |
info: console.info | |
} | |
function logLine (logLine) { | |
var line1 = JSON.stringify({ 'index': { '_index': sematextLogToken, '_type': 'browser_logs' } }) | |
logBuffer = logBuffer + (line1 + '\n' + logLine + '\n') | |
} | |
function sematextShipLogs () { | |
if (lineCount === 0) { | |
return | |
} | |
const http = new XMLHttpRequest() | |
http.open('POST', sematextUrl, true) | |
http.setRequestHeader('Content-type', 'application/json') | |
http.send(logBuffer) | |
http.onresponse = consoleLog | |
logBuffer = '' | |
lineCount = 0 | |
} | |
function sematextLog (severity) { | |
let args = new Array(arguments).slice(1) | |
consoleFunctions[severity](...args) | |
if (arguments.length > 1) { | |
if (typeof arguments[1] === 'string') { | |
logLine(JSON.stringify({ | |
message: arguments[1], | |
'@timestamp': new Date(), | |
sessionId: String(sessionId), | |
severity: severity, | |
location: window.location | |
})) | |
} else { | |
logLine(JSON.stringify({ | |
msg: arguments, | |
'@timestamp': new Date(), | |
sessionId: String(sessionId), | |
severity: severity, | |
location: window.location | |
})) | |
} | |
lineCount++ | |
if (lineCount > 100) { | |
sematextShipLogs() | |
} | |
} | |
} | |
console.log = function () { sematextLog('info', ...arguments) } | |
console.error = function () { sematextLog('error', ...arguments) } | |
console.warn = function () { sematextLog('warn', ...arguments) } | |
console.debug = function () { sematextLog('debug', ...arguments) } | |
setInterval(sematextShipLogs, 5000) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment