46045-syslab/syslab-python/syslab/comm/logrec.py

81 lines
2.5 KiB
Python

###############################################################
# SYSLAB remote logger v0.9
# utility to display and record log events
# usage: move bash to target log directory, then call
# python <path to syslab-python>/syslab/comm/logrec.py
#
# Author: Kai Heussen
# Date: 2023/06/18
###############################################################
import pickle
import logging
import socket
from syslab import config
# import sys
from time import time
# from json import dump
BASIC = True
FILE = True
FILE_RAW = False # TODO: write a JSON formatter - based on https://stackoverflow.com/questions/50144628/python-logging-into-file-as-a-dictionary-or-json
logtype = "EV"
time=time()
logfile =f"syslab_{logtype}_log_{time:.00f}.txt"
logfile_raw =f"syslab_{logtype}_log_{time:.00f}.raw" # not yet json
DEFAULT_PORT = config.REMOTE_PORT_SP if logtype == "SP" else config.REMOTE_PORT_EV
port = DEFAULT_PORT
#simple_formats = '%(asctime)s - %(name)s - %(message)s'
simple_formats = '%(asctime)s - %(module)s - %(message)s'
#formats='foo: %(levelname)s - %(module)s.%(funcName)s - %(message)s'
event_log_formatter = '%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(module)s - %(funcName)s - %(message)s'
formats = simple_formats
formatter = logging.Formatter(formats)
if BASIC:
logging.basicConfig(format=formats)
else:
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
if FILE:
handler = logging.FileHandler(logfile)
handler.setLevel(logging.INFO)
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
logger = logging.getLogger()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', port))
print(f'Listening for log records on port {port}...')
if FILE:
print(f'recording log entries in file: {logfile}')
if FILE_RAW:
print(f'recording raw log entries in file: {logfile_raw}')
try:
while True:
d, _ = s.recvfrom(1024)
msg = pickle.loads(d[4:])
logrec = logging.makeLogRecord(msg)
logger.handle(logrec)
if FILE_RAW:
with open(logfile_raw, 'a') as file:
# dump(logrec, file) # requires a JSON formatter
file.write(f'{logrec.__str__() }\n') # Write a newline for each measurement to make loading easier
#print(log)
finally:
s.close()
if FILE_RAW:
file.close()