This repository has been archived on 2025-06-01. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
compLIB/client_s1/compLib/LogstashLogging.py
Konstantin Lampalzer 9b567b8c6c Protobuf prototype
2022-03-18 18:11:16 +01:00

102 lines
2.7 KiB
Python

import logging
import os
import sys
import requests
from logstash_async.transport import HttpTransport
from logstash_async.handler import AsynchronousLogstashHandler
EXTENSIVE_LOGGING = os.getenv("EXTENSIVE_LOGGING", "False")
if EXTENSIVE_LOGGING == "True":
EXTENSIVE_LOGGING = True
else:
EXTENSIVE_LOGGING = False
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, textio, log_level=logging.INFO):
self.logger = logging.getLogger('logstash')
self.console = textio
self.log_level = log_level
self.linebuf = ''
def write(self, buf):
self.console.write(buf)
temp_linebuf = self.linebuf + buf
for line in buf.splitlines(True):
self.linebuf += line
def flush(self):
if self.linebuf != '':
self.logger.log(self.log_level, self.linebuf.rstrip())
self.linebuf = ''
self.console.flush()
asynchronousLogstashHandler.flush()
if EXTENSIVE_LOGGING:
try:
r = requests.get(f"https://{host}:{port}")
if r.status_code == 401:
logstash_logger.addHandler(asynchronousLogstashHandler)
so = StreamToLogger(sys.stdout, logging.INFO)
sys.stdout = so
se = StreamToLogger(sys.stderr, logging.ERROR)
sys.stderr = se
else:
print(f"Could not connect to {host} -> ERROR CODE: {r.status_code}!")
except requests.exceptions.ConnectionError as identifier:
print(f"Could not connect to {host}!")
print(f"Error loading logger was -> {identifier}")
else:
print("Extensive logging is disabled! No logs will be sent over network...")
class Logging(object):
"""Can be used to manually use the logger or turn up the logging level used for debugging this library.
"""
@staticmethod
def get_logger() -> logging.Logger:
"""Get the logger object used to communicate with logstash
:return: Python logger
:rtype: logging.Logger
"""
return logstash_logger
@staticmethod
def set_debug():
"""Turns up the logging level of the library to debug. Should be used, when debugging with the
Competition organizers
"""
logstash_logger.setLevel(logging.DEBUG)