Skip to content

Instantly share code, notes, and snippets.

@MattBlack85
Created December 18, 2018 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattBlack85/86d620a306f16416a7f96a1a035984dc to your computer and use it in GitHub Desktop.
Save MattBlack85/86d620a306f16416a7f96a1a035984dc to your computer and use it in GitHub Desktop.
import logging
import time
from logging.handlers import SocketHandler
logger = logging.getLogger('test')
class BinarySocketHandler(SocketHandler):
def prepare_record(self, record):
return self.format(record).encode()
def emit(self, record):
"""
Emit a record.
Pickles the record and writes it to the socket in binary format.
If there is an error with the socket, silently drop the packet.
If there was a problem with the socket, re-establishes the
socket.
"""
try:
s = self.prepare_record(record)
print('RECORD:', s)
self.send(s)
except Exception:
self.handleError(record)
def send(self, s):
"""
Send a pickled string to the socket.
This function allows for partial sends which can happen when the
network is busy.
"""
if self.sock is None:
self.createSocket()
# self.sock can be None either because we haven't reached the retry
# time yet, or because we have reached the retry time and retried,
# but are still unable to connect.
if self.sock:
try:
print('SENDING DATA OVER THE SOCKET:', s)
self.sock.sendall(s)
except OSError: # pragma: no cover
self.sock.close()
self.sock = None # so we can call createSocket next time
def main():
shandler = BinarySocketHandler('/tmp/alf.sock', None)
chandler = logging.StreamHandler()
formatter = logging.Formatter(
'{"time":"%(asctime)s","name":"%(name)s","levelname":"%(levelname)s","message":"%(message)s","pathname":"%(pathname)s"}')
logger.setLevel(10)
shandler.setFormatter(formatter)
chandler.setFormatter(formatter)
logger.addHandler(shandler)
logger.addHandler(chandler)
for _ in range(10):
#time.sleep(0.001)
logger.debug(f'test {_}')
if __name__ == '__main__':
main()
@MattBlack85
Copy link
Author

run with python send_logs.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment