proper logging, add signal handler for graceful termination

This commit is contained in:
2025-05-23 13:52:42 +02:00
parent 04bf09ae5a
commit ef35d18f37
6 changed files with 52 additions and 39 deletions

View File

@ -1,6 +1,7 @@
import socket
import time
import re
import logging
from select import select
@ -27,10 +28,10 @@ class Base:
select_write = {}
def close(self):
print('CLOSE BASE')
logging.info('CLOSE BASE')
def finish_events(self, *args):
print('FINISH BASE')
logging.info('FINISH BASE')
def short_hostname(host):
@ -74,7 +75,7 @@ class Stream(Base):
self.connect()
self.init(**kwds)
except Exception as e:
print('FAIL', self.uri, repr(e))
logging.info('failled connecting %s %r', self.uri, e)
raise
def connect(self):
@ -84,7 +85,7 @@ class Stream(Base):
host, _, port = self.uri.partition(':')
# try to convert uri to host name
self.uri = self.tags['stream'] = f'{short_hostname(host)}:{port}'
print(f'{host}:{port}', '=', self.uri, 'connected')
logging.info('connected %s:%s = %s', host, port, self.uri)
self._buffer = []
self._deadline = INF
self._next_connect = 0
@ -104,7 +105,7 @@ class Stream(Base):
if self.socket is None:
return
self.select_read.pop(self.socket.fileno(), None)
print(self.uri, 'close socket')
logging.info('close socket %s', self.uri)
try:
self.socket.shutdown(socket.SHUT_RDWR)
except socket.error:
@ -130,10 +131,9 @@ class Stream(Base):
self.dead = min(now, self._last_live + 1)
return True
if self._deadline == INF:
print(f'error "{e}" connecting to {self.uri} retrying for {self.max_offline} sec')
logging.info(f'error %r connecting to %s retrying for %s sec',
e, self.uri, self.max_offline)
self._deadline = now + self.max_offline
else:
print('.', end='', flush=True)
self._next_connect = now + 0.5
return True
return False
@ -163,7 +163,7 @@ class Stream(Base):
now = time.time()
if now > self._next_ping:
if self._next_ping == self._ping_deadline:
print(self.uri, 'no pong')
self.log.info('no pong from %s', self.uri)
self.close()
return
self.ping()
@ -280,13 +280,13 @@ class EventStream:
stream = self.streams.get(uri)
if stream:
stream.tags.update(kwargs)
print('update stream', uri, kwargs)
logging.info('update stream %s %r', uri, kwargs)
else:
try:
self.streams[uri] = stream = streamcls(uri, **kwargs)
print('added stream', uri, kwargs)
logging.info('added stream %s %r', uri, kwargs)
except Exception as e:
print('can not connect to', uri, repr(e), streamcls)
logging.warning('can not connect to %s %r %r', uri, e, streamcls)
continue
device = stream.tags.get('device')
events.append(('stream', kwargs.get('instrument', ''),