Skip to content

Instantly share code, notes, and snippets.

@coreequip
Last active July 15, 2019 08:09
Show Gist options
  • Save coreequip/82abef5d982a87e2eeda4d4db36ace7d to your computer and use it in GitHub Desktop.
Save coreequip/82abef5d982a87e2eeda4d4db36ace7d to your computer and use it in GitHub Desktop.
Groovy Util.Logging Graylog Handler
package com.acme.logging
import groovy.json.JsonOutput
import java.nio.charset.StandardCharsets
import java.util.logging.Handler
import java.util.logging.Level
import java.util.logging.LogRecord
class GrayLogHandler extends Handler {
static final String NAMESPACE_BASE = 'com.acme'
static final LEVELMAP = [
(Level.SEVERE) : 1,
(Level.WARNING): 2,
(Level.INFO) : 3,
(Level.CONFIG) : 4,
(Level.FINE) : 5,
(Level.FINER) : 6,
(Level.FINEST) : 7
]
InetAddress host
int port
DatagramSocket ds = new DatagramSocket()
GrayLogHandler(String host, int port) {
this.host = InetAddress.getByName(host)
this.port = port
}
@Override
void publish(LogRecord record) {
def gelf = [
version : '1.1',
host : InetAddress.localHost.canonicalHostName,
level : LEVELMAP[record.level],
short_message: record.message.split(/\n/)?.first() ?: ''
]
if (gelf.short_message != record.message)
gelf.full_message = record.message
if (this.level == Level.ALL && !record.sourceClassName.startsWith(NAMESPACE_BASE)) {
new Throwable().getStackTrace().each { StackTraceElement ste ->
if (ste.className == this.class.name || !ste.className.startsWith(NAMESPACE_BASE)) return
gelf._source_class = ste.className
gelf._source_method = ste.methodName
gelf.file = ste.fileName
gelf.line = ste.lineNumber
}
}
if (record.thrown) {
def sw = new StringWriter()
record.thrown.printStackTrace(new PrintWriter(sw))
gelf['_StackTrace'] = sw.toString()
}
byte[] buffer = JsonOutput.toJson(gelf).getBytes(StandardCharsets.UTF_8)
ds.send(new DatagramPacket(buffer, buffer.length, host, port))
}
@Override
void flush() {
}
@Override
void close() throws SecurityException {
}
}
package com.acme.logtest
import com.acme.logging.GrayLogHandler
import java.util.logging.Level
import java.util.logging.LogManager
import java.util.logging.Logger
class GrayLogUsage {
static void main(String[] args) {
final Logger log = Logger.getLogger('GRAY')
LogManager.logManager.reset()
log.setLevel(Level.ALL)
log.addHandler(new GrayLogHandler('graylog.local', 12345))
log.info('TEST')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment