Add logstash logger

This commit is contained in:
Konstantin Lampalzer 2021-01-16 20:44:53 +01:00
parent 1b6fd1cfdf
commit b2a085eab3
No known key found for this signature in database
GPG key ID: 9A60A522835A2AD9
4 changed files with 80 additions and 4 deletions

View file

@ -0,0 +1,72 @@
import logging
import sys
import requests
from logstash_async.transport import HttpTransport
from logstash_async.handler import AsynchronousLogstashHandler
host = 'logs.robo4you.at'
port = 443
logstash_logger = logging.getLogger('logstash')
logstash_logger.setLevel(logging.INFO)
transport = HttpTransport(
host,
port,
username="robo",
password="competition",
timeout=10.0,
)
asynchronousLogstashHandler = AsynchronousLogstashHandler(
host,
port,
transport=transport,
database_path='logstash_test.db'
)
class StreamToLogger(object):
"""
Fake file-like stream object that redirects writes to a logger instance.
"""
def __init__(self, log_level=logging.INFO):
self.logger = logging.getLogger('logstash')
self.console = sys.stdout
self.log_level = log_level
self.linebuf = ''
def write(self, buf):
self.console.write(buf)
temp_linebuf = self.linebuf + buf
self.linebuf = ''
for line in temp_linebuf.splitlines(True):
if line[-1] == '\n':
self.logger.log(self.log_level, line.rstrip())
else:
self.linebuf += line
def flush(self):
self.console.flush()
if self.linebuf != '':
self.logger.log(self.log_level, self.linebuf.rstrip())
self.linebuf = ''
asynchronousLogstashHandler.flush()
try:
requests.head(f"http://{host}:{port}")
logstash_logger.addHandler(asynchronousLogstashHandler)
sl = StreamToLogger(logging.INFO)
sys.stdout = sl
except requests.exceptions.ConnectionError as identifier:
print(f"Could not connect to {host}!")
pass