Skip to content

Instantly share code, notes, and snippets.

@megastef
Last active January 23, 2020 16:15
Show Gist options
  • Save megastef/0c9839faa499f089bc1440fa65d3d56a to your computer and use it in GitHub Desktop.
Save megastef/0c9839faa499f089bc1440fa65d3d56a to your computer and use it in GitHub Desktop.
Log to Sematext From Web browser
<html>
<body>
<script>
(function () {
const sematextLogToken = 'c0e39f27-xxxx-xxxx-9f27-8818a4f0b59d'
var sematextUrl = `https://logsene-receiver.sematext.com/${sematextLogToken}/_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)
})()
console.log('Hello from Browser')
console.error('Error from Browser')
console.log({'name': 'stefan'}, 5, window.name)
console.log({'name': 'stefan'}, '5', 10, window.name)
</script>
</body>
Hello
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment