Uno-Dan

Client app

May 13th, 2019
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. import logging
  2.  
  3. from time import sleep
  4. from random import randint
  5. from socket import gethostname, gethostbyname
  6. from logging import Formatter, getLogger, INFO, DEBUG, WARNING, ERROR, CRITICAL, NOTSET
  7. from zmq import Context, ssh
  8. from zmq.backend.cython.constants import PUB
  9. from zmq.log.handlers import PUBHandler
  10.  
  11. LOGLEVELS = (
  12.     'NOTSET',
  13.     'DEBUG',
  14.     'INFO',
  15.     'WARNING',
  16.     'ERROR',
  17.     'CRITICAL'
  18. )
  19.  
  20. LOGGER_PORT = '17770'
  21. LOGGER_SERVER = '192.168.10.216'
  22. LOGGER_USER = f'dan@{LOGGER_SERVER}'
  23. LOGGER_CONNECTION = f'tcp://{LOGGER_SERVER}:{LOGGER_PORT}'
  24. LOGGER_FORMAT = '%(levelname)s:%(asctime)s,%(msecs)d:%(process)d:%(name)s:%(filename)s:%(funcName)s:' \
  25.                 '%(lineno)d:%(message)s'
  26.  
  27.  
  28. def _check_level(loglevel):
  29.     if isinstance(loglevel, str):
  30.         numeric_level = getattr(logging, loglevel.upper(), None)
  31.     elif isinstance(loglevel, int):
  32.         numeric_level = loglevel if loglevel in range(10, 50, 10) else NOTSET
  33.     else:
  34.         raise ValueError(f'Invalid log level: {loglevel}')
  35.  
  36.     return numeric_level
  37.  
  38.  
  39. class TestModule:
  40.     def __init__(self, **kwargs):
  41.         self.name = __class__.__name__
  42.         self.loglevel = _check_level(kwargs.get('loglevel', WARNING))
  43.         self.hostname = gethostname()
  44.         self.ipaddr = gethostbyname(self.hostname)
  45.  
  46.     def start(self):
  47.         ctx = Context()
  48.         socket = ctx.socket(PUB)
  49.  
  50.         ssh.tunnel_connection(socket, LOGGER_CONNECTION, LOGGER_USER)
  51.         handler = PUBHandler(socket)
  52.  
  53.         formatter = Formatter(LOGGER_FORMAT, datefmt='%Y/%m/%d %H:%M:%S')
  54.         for level in [DEBUG, INFO, WARNING, ERROR, CRITICAL]:
  55.             handler.formatters[level] = formatter
  56.  
  57.         remote_logger = getLogger(self.name)
  58.         remote_logger.addHandler(handler)
  59.         remote_logger.setLevel(self.loglevel)
  60.         remote_logger.info(f'{self.hostname}:{self.ipaddr}:MyApp:started')
  61.  
  62.         while True:
  63.             msg = f'{self.hostname}:{self.ipaddr}:Test message client'
  64.             level = LOGLEVELS[randint(1, 5)]
  65.             remote_logger.log(getattr(logging, level), msg)
  66.  
  67.             sleep(randint(1, 2))
Advertisement
Add Comment
Please, Sign In to add comment