Created
December 18, 2018 10:55
-
-
Save MattBlack85/86d620a306f16416a7f96a1a035984dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
run with
python send_logs.py