78 lines
2 KiB
Python
78 lines
2 KiB
Python
import logging
|
|
import sys
|
|
import requests
|
|
|
|
from logstash_async.transport import HttpTransport
|
|
from logstash_async.handler import AsynchronousLogstashHandler
|
|
|
|
host = 'logstash.robo4you.at'
|
|
port = 443
|
|
|
|
logstash_logger = logging.getLogger('logstash')
|
|
logstash_logger.setLevel(logging.INFO)
|
|
|
|
transport = HttpTransport(
|
|
host,
|
|
port,
|
|
username="robo",
|
|
password="competition",
|
|
timeout=60.0,
|
|
)
|
|
|
|
asynchronousLogstashHandler = AsynchronousLogstashHandler(
|
|
host,
|
|
port,
|
|
transport=transport,
|
|
database_path='logs.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:
|
|
r = requests.head(f"http://{host}:{port}")
|
|
if r.status_code == 400:
|
|
logstash_logger.addHandler(asynchronousLogstashHandler)
|
|
|
|
sl = StreamToLogger(logging.INFO)
|
|
sys.stdout = sl
|
|
else:
|
|
print(f"Could not connect to {host} -> {r.status_code}!")
|
|
|
|
except requests.exceptions.ConnectionError as identifier:
|
|
print(f"Could not connect to {host}!")
|
|
pass
|
|
|
|
class Logging(object):
|
|
|
|
@staticmethod
|
|
def get_logger() -> logging.Logger:
|
|
return logstash_logger
|
|
|
|
@staticmethod
|
|
def set_debug():
|
|
logstash_logger.setLevel(logging.DEBUG)
|