From cfd9392c0216a876579eae221ac9b78d75a02bc2 Mon Sep 17 00:00:00 2001 From: nikolay Date: Fri, 24 Jul 2020 13:19:44 +0200 Subject: [PATCH] Change logging --- .gitignore | 3 +++ README.md | 16 ++++++------ daemon.py | 2 +- dwg.py | 52 ++++++++++++++++++++++---------------- dwgc.py | 59 +++++++++++++++++--------------------------- dwgconfig.py | 5 ++-- dwgconfig.py.example | 20 +++++++++++++++ logger.py | 21 ++++++++++++++++ 8 files changed, 110 insertions(+), 68 deletions(-) create mode 100644 .gitignore mode change 100755 => 100644 README.md create mode 100644 dwgconfig.py.example create mode 100644 logger.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..02c8c5c --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.idea +dwgconfig.py +*.pyc \ No newline at end of file diff --git a/README.md b/README.md old mode 100755 new mode 100644 index a2134f9..ff454d9 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ Overview ======== -This Script for VoIP GSM Module - Dinstar DWG 2000: sending and receiveing SMS/USSD from/to gateway (written on Python2). +This Script for VoIP GSM Module - Dinstar DWG 2000: sending and receiving SMS/USSD from/to gateway (written on Python2). How to compile ============== @@ -20,6 +20,8 @@ How to install - On/Off debugging (debug) - Path for pidfile, if running as daemon (pidfile) - Path to logfile, if running as daemon (logfile) +- Format of log line (log_format) +- Format of date in log line (log_date_format) How to use ========== @@ -31,13 +33,13 @@ How to use - restart: restarting script as daemon - help: showing help message for arguments - Sending SMS format: -- First line - phone number -- Second line - port -- Other lines - message for send + - First line - phone number + - Second line - port + - Other lines - message for send - Received message as eml format. -- Sending USSD-command format -- First line - port -- Second line - USSD-command (ex. *100#) +- Sending USSD-command format: + - First line - port + - Second line - USSD-command (ex. *100#) - Received message as eml format. Depends diff --git a/daemon.py b/daemon.py index 8bef510..be87b1d 100644 --- a/daemon.py +++ b/daemon.py @@ -7,6 +7,7 @@ import atexit from signal import SIGTERM + class Daemon: """ A generic daemon class. @@ -63,7 +64,6 @@ def daemonize(self): def delpid(self): os.remove(self.pidfile) - def start(self): try: pf = file(self.pidfile, 'r') diff --git a/dwg.py b/dwg.py index d4b9aad..6028c9e 100644 --- a/dwg.py +++ b/dwg.py @@ -1,28 +1,35 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- + import dwgconfig import socket +import logging from sys import argv -from dwgc import DWGD, logger +from dwgc import DWGD from daemon import Daemon +from logger import create_logger + def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('', dwgconfig.port)) sock.listen(1) - logger('[SYSTEM] Server listening...', False) + logging.info('[SYSTEM] Server listening...') try: while True: conn, addr = sock.accept() - logger('[SYSTEM] Gateway connected %s' % addr[0], False) + logging.info('[SYSTEM] Gateway connected %s' % addr[0]) DWGD(conn) - logger('[SYSTEM] Gateway disconnected', False) + logging.info('[SYSTEM] Gateway disconnected') except KeyboardInterrupt: + logging.info('[SYSTEM] Daemon keyboard interrupted') exit() finally: + logging.info('[SYSTEM] Daemon socket closed') sock.close() + def usage(): print """ Script usage parameters: @@ -33,34 +40,37 @@ def usage(): help - Show this help """ + class DWGDaemon(Daemon): def run(self): main() + """ Check agrvs """ if __name__ == "__main__": daemon = DWGDaemon(dwgconfig.pidfile) if len(argv) == 2: - if argv[1] == 'debug': - dwgconfig.debug = True - dwgconfig.as_daemon = False - logger('[SYSTEM] Debug mode is on', True) - main() - elif argv[1] == 'start': - logger('[SYSTEM] Daemon started', True) - daemon.start() - elif argv[1] == 'stop': - logger('[SYSTEM] Daemon stopped', True) - daemon.stop() - elif argv[1] == 'restart': - logger('[SYSTEM] Daemon restarted', True) - daemon.restart() - else: + allowed_argv = ['debug', 'start', 'stop', 'restart'] + if argv[1] not in allowed_argv: usage() exit(2) - exit(0) + else: + create_logger(argv[1] == 'debug') + if argv[1] == 'debug': + logging.debug('[SYSTEM] Debug mode is on') + main() + elif argv[1] == 'start': + logging.info('[SYSTEM] Daemon started') + daemon.start() + elif argv[1] == 'stop': + logging.info('[SYSTEM] Daemon stopped') + daemon.stop() + elif argv[1] == 'restart': + logging.info('[SYSTEM] Daemon restarted') + daemon.restart() + exit(0) else: usage() - exit(2) \ No newline at end of file + exit(2) diff --git a/dwgc.py b/dwgc.py index 7309870..3e0914c 100644 --- a/dwgc.py +++ b/dwgc.py @@ -8,6 +8,7 @@ from time import time, strftime import codecs import os +import logging from subprocess import Popen @@ -40,19 +41,15 @@ def getDWG(self): exit() except: break - if not self.ping_t is None: - self.ping_t.cancel() - if not self.check_t is None: - self.check_t.cancel() + self.stop_ping() self.conn.close() - def parseDWG(self, data): """ Parsing DWG Messages """ if data: - logger('[PROCESS] <- %s' % data.encode("hex"), True) + logging.debug('[PROCESS] <- %s' % data.encode("hex")) while data: header = {'len': unpack('!L', data[0:4])[0], 'id': {'mac': unpack('!6s', data[4:10])[0], @@ -74,7 +71,7 @@ def parseType(self, htype, data): """ sdata = {'type': 0, 'body': ''} - if htype == 0: # recieved keep alive + if htype == 0: # received keep alive self.ping_count = 0 elif htype == 7: # Status message sdata['type'] = 8 @@ -109,9 +106,9 @@ def parseType(self, htype, data): if body['login'] == dwgconfig.login and body['password'] == dwgconfig.password: sdata['type'] = 16 sdata['body'] = pack('!?', False) - logger('[SYSTEM] Authentication success', False) + logging.info('[SYSTEM] Authentication success') else: - logger('[SYSTEM] Authentication failed', False) + logging.info('[SYSTEM] Authentication failed') elif htype == 515: # Call state report sdata['type'] = 516 sdata['body'] = pack('!?', False) @@ -122,10 +119,7 @@ def pingDWG(self): Ping DWG """ if self.ping_count > 2: - if not self.ping_t is None: - self.ping_t.cancel() - if not self.check_t is None: - self.check_t.cancel() + self.stop_ping() self.conn.close() else: sdata = {'type': 0, @@ -147,7 +141,7 @@ def sendDWG(self, header, sdata): pkt += pack('!H', sdata['type']) pkt += pack('!H', 0) pkt += sdata['body'] - logger('[PROCESS] -> %s' % pkt.encode("hex"), True) + logging.debug('[PROCESS] -> %s' % pkt.encode("hex")) self.conn.send(pkt) def create_header(self): @@ -179,9 +173,9 @@ def saveSMS(self, body): sms.write(body['content'].decode('utf-16-be')) sms.close() Popen(dwgconfig.run_program) - logger('[DATA] Received SMS from number %s' % body['number'], False) + logging.info('[DATA] Received SMS from number %s' % body['number']) except: - logger('[DATA] Received unknown SMS', False) + logging.info('[DATA] Received unknown SMS') def saveUSSD(self, body): """ @@ -202,23 +196,24 @@ def saveUSSD(self, body): elif body['encoding'] == 1: ussd.write(body['content'].decode('utf-16-be')) ussd.close() - logger('[DATA] Received USSD from port %s' % body['port'], False) + logging.info('[DATA] Received USSD from port %s' % body['port']) except: - logger('[DATA] Received unknown USSD', False) - + logging.info('[DATA] Received unknown USSD') def checkSMS(self): """ Check SMS/USSD in folders """ files = [f for f in os.listdir(dwgconfig.send_path) if os.path.isfile(os.path.join(dwgconfig.send_path, f))] + port = None + number = None if len(files): sms = codecs.open(dwgconfig.send_path + files[0], 'r', 'utf-8').readlines() f_send = True if len(sms) > 2: try: number = str(sms[0].strip()) - if not number.isdigit(): f_send = False + # if not number.isdigit(): f_send = False except: f_send = False try: @@ -233,7 +228,7 @@ def checkSMS(self): sdata = {'type': 1, 'body': pack('!BBBB24sH%ds' % len(content), port, 1, 0, 1, number, len(content), content)} self.sendDWG(self.create_header(), sdata) - logger('[DATA] Sending SMS to number %s' % number, False) + logging.info('[DATA] Sending SMS to number %s' % number) os.remove(dwgconfig.send_path + files[0]) else: files = [f for f in os.listdir(dwgconfig.ussd_send_path) if os.path.isfile(os.path.join(dwgconfig.ussd_send_path, f))] @@ -253,23 +248,13 @@ def checkSMS(self): sdata = {'type': 9, 'body': pack('!BBH%ds' % len(number), port, 1, len(number), number)} self.sendDWG(self.create_header(), sdata) - logger('[DATA] Sending USSD to port %s to number %s' % (port, number), False) + logging.info('[DATA] Sending USSD to port %s to number %s' % (port, number)) os.remove(dwgconfig.ussd_send_path + files[0]) self.check_t = Timer(self.check_timer, self.checkSMS) self.check_t.start() - -def logger(message, debug): - now = strftime('%d.%m.%Y %H:%M:%S') - line = '[%s] %s' % (now, message) - if dwgconfig.as_daemon: - line += '\n' - if debug and dwgconfig.debug: - open(dwgconfig.logfile, 'a').write(line) - elif not debug: - open(dwgconfig.logfile, 'a').write(line) - else: - if debug and dwgconfig.debug: - print line - elif not debug: - print line \ No newline at end of file + def stop_ping(self): + if self.ping_t is not None: + self.ping_t.cancel() + if self.check_t is not None: + self.check_t.cancel() diff --git a/dwgconfig.py b/dwgconfig.py index a24138d..86dce54 100644 --- a/dwgconfig.py +++ b/dwgconfig.py @@ -13,7 +13,8 @@ pidfile = '/var/run/dwg_server.pid' # PID file path (for daemon) logfile = '/var/log/dwg_server.log' # Log file path (for daemon) -as_daemon = True +log_format = '[%(asctime)s] [%(levelname)s] %(message)s' # Log file format +log_date_format = '%d.%m.%Y %H:%M:%S' # Log file date format if __name__ == '__main__': - print 'Config file for Dinstar DWG Gateways!' \ No newline at end of file + print 'Config file for Dinstar DWG Gateways!' diff --git a/dwgconfig.py.example b/dwgconfig.py.example new file mode 100644 index 0000000..86dce54 --- /dev/null +++ b/dwgconfig.py.example @@ -0,0 +1,20 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +port = 12000 # DWG Gateway port +login = 'test' # DWG API Login (from API 2.0) +password = 'test' # DWG API Password (from API 2.0) +income_path = '/var/spool/dwgp/incoming/' # SMS income path +send_path = '/var/spool/dwgp/send/' # SMS send path +ussd_income_path = '/var/spool/dwgp/ussd_incoming/' # USSD income path +ussd_send_path = '/var/spool/dwgp/ussd_send' # USSD send path +run_program = '/etc/local_scripts/radius2.php' # External program after receiving SMS +debug = True # On/OFF Debug + +pidfile = '/var/run/dwg_server.pid' # PID file path (for daemon) +logfile = '/var/log/dwg_server.log' # Log file path (for daemon) +log_format = '[%(asctime)s] [%(levelname)s] %(message)s' # Log file format +log_date_format = '%d.%m.%Y %H:%M:%S' # Log file date format + +if __name__ == '__main__': + print 'Config file for Dinstar DWG Gateways!' diff --git a/logger.py b/logger.py new file mode 100644 index 0000000..8e6b029 --- /dev/null +++ b/logger.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import logging +import dwgconfig + + +def create_logger(debug=False): + log = logging.getLogger() + formatter = logging.Formatter(dwgconfig.log_format, datefmt=dwgconfig.log_date_format) + log_level = logging.DEBUG + if debug: + log_handler = logging.StreamHandler() + else: + if not dwgconfig.debug: + log_level = logging.INFO + log_handler = logging.FileHandler(dwgconfig.logfile) + log_handler.setLevel(log_level) + log_handler.setFormatter(formatter) + log.setLevel(log_level) + log.addHandler(log_handler)