diff --git a/f7/udplog.py b/f7/udplog.py index 086b67d..9329b64 100644 --- a/f7/udplog.py +++ b/f7/udplog.py @@ -1,20 +1,89 @@ # -*- coding: utf-8 -*- -class Udplog: +import time +import datetime +import traceback +import _thread +import threading +class _LocalLogNode: + def __init__(self, msg): + self.msg = msg + self.nextNode = None + +class _UdpLog: _instance = None @classmethod def instance(cls): - if not _instance: - _instance = UdpLog() - return _instance + if not cls._instance: + cls._instance = _UdpLog() + return cls._instance def __init__(self): - pass + self._topNode = None + self._botNode = None + self._workNode = None + self._msgLock = threading.Lock() def init(self): - pass + _thread.start_new_thread(self._saveToFile, ()) def unInit(self): pass + + def info(self, msg): + self._addLog(str(datetime.datetime.now()) + '[INFO]' + str(msg)) + + def debug(self, msg): + self._addLog(str(datetime.datetime.now()) + '[DEBUG]' + str(msg)) + + def warning(self, msg): + self._addLog(str(datetime.datetime.now()) + '[WARNING]' + str(msg)) + + def error(self, msg): + self._addLog(str(datetime.datetime.now()) + '[ERROR]' + str(msg)) + + def _addLog(self, msg): + node = _LocalLogNode(msg) + self._msgLock.acquire() + try: + if self._botNode == None: + self._topNode = node + self._botNode = node + else: + self._botNode.nextNode = node + self._botNode = node + except: + traceback.print_exc() + finally: + self._msgLock.release() + + + def _saveToFile(self): + try: + while True: + if not self._workNode and self._topNode: + self._msgLock.acquire() + try: + self._workNode = self._topNode + self._topNode = None + self._botNode = None + finally: + self._msgLock.release() + if self._workNode: + filename = datetime.datetime.now().strftime('log%Y-%m-%d.log') + try: + with open(os.path.join(LOG_DIR, filename), 'a') as f: + while self._workNode: + nextNode = self._workNode.nextNode + f.write(self._workNode.msg + '\r\n') + self._workNode = nextNode + except Exception as e: + print(str(e), flush=True) + time.sleep(10) + except: + traceback.print_exec() + +def instance(): + return _UdpLog.instance() diff --git a/test/app.py b/test/app.py new file mode 100644 index 0000000..4afb760 --- /dev/null +++ b/test/app.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- + +import sys +import time + +sys.path.append('..') + +import f7.udplog + +f7.udplog.instance().init() +time.sleep(5)