Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os, sys, socket, threading, traceback, time, smtplib, ssl, psutil, ctypes, configparser
- from email.mime.application import MIMEApplication
- from email.mime.multipart import MIMEMultipart
- from email.mime.text import MIMEText
- from email.utils import COMMASPACE, formatdate
- if os.name == 'nt':
- import win32api, win32con
- pass
- if getattr(sys, 'frozen', False):
- exe_path = os.path.dirname(sys.executable)
- elif __file__:
- exe_path = os.path.dirname(os.path.abspath(__file__))
- pass
- ##For testing:
- import socket, traceback, os, sys, time
- class Socket_Log():
- def __inti__(self):
- self.sock = None
- create_socket()
- def log(self, log):
- try:
- self.sock.sendall(str("log: %s, %s\r" %(strtime, log)).encode())
- except:
- self.create_socket()
- def error(self, error):
- try:
- exc_type, exc_obj, exc_tb = sys.exc_info()
- trace_stack = traceback.extract_tb(exc_tb)[-1]
- trace_format = "Error in file "+str(trace_stack[0])+"\r on line "+str(trace_stack[1])+", from module '"+str(trace_stack[2])+"'\r "+str(trace_stack[3])
- strtime = str(time.strftime("%d-%m-%Y,(%z),%H:%M:%S"))
- self.sock.sendall(str("error: %s, %s, %s\r" %(strtime, error, trace_format)).encode())
- except:
- self.create_socket()
- def create_socket(self):
- self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.sock.connect((socket.gethostname(), 6085))
- def quitter(self):
- self.sock.sendall(b'exit')
- ##Add the above code to any program.
- ##Initilise the logger functions:
- ##imports
- import time as pytime #fix so can use datetime time alongside
- import sys, traceback, os, subprocess, tempfile, psutil
- if os.name == 'nt': #windows fix
- import win32api, win32con
- pass
- if getattr(sys, 'frozen', False): #windows path fix
- #os.chdir(sys._MEIPASS)
- exe_path = os.path.dirname(sys.executable)
- elif __file__:
- exe_path = os.path.dirname(os.path.abspath(__file__))
- pass
- tmp = tempfile.mkdtemp()
- ##Proc Required:
- proc = [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if str(os.getpid()) in str(p.info['pid'])][0]
- proc = proc['name']
- ##Initilise:
- print("%s\\logger\\Logger.exe, '%s', '%s'" %(exe_path, tmp, proc))
- subprocess.Popen(['%s\\logger\\Logger.exe' %(exe_path), tmp, proc])
- pytime.sleep(2)
- logger = Socket_Log()
- ##use try/excoet Casees
- try:
- #some code
- except Exception as err:
- exc_type, exc_obj, exc_tb = sys.exc_info()
- logger.error("MyFunction failed\n%s, %s, %s, %s" %(err, exc_type, exc_obj, traceback.print_tb(exc_tb)))
- class socket_logger:
- def __init__(self, tmp, proc):
- self.proc = proc
- self.log = []
- self.tmpdir = tmp
- self.file = "debug.log"
- self.endstate = False
- self.quit = False
- self.error_state = False
- self.config = {}
- def read_config(self):
- config = configparser.ConfigParser()
- config.read(exe_path+'\\logger.ini')
- details = {}
- for key, value in config['EMAIL'].items():
- print(key, value)
- details[key] = value
- return details
- def starter(self):
- self.config = self.read_config()
- t=threading.Thread(target=self.app_run)
- t.start()
- time.sleep(1)
- socket.setdefaulttimeout(5)
- serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- serversocket.bind((socket.gethostname(), 6085))
- serversocket.listen(1)
- while not self.quit:
- try:
- clientsocket, address = serversocket.accept()
- break
- except:
- pass
- while not self.quit:
- while not self.quit:
- try:
- data = clientsocket.recv(65565)
- break
- except:
- pass
- if data == b'':
- try:
- clientsocket.send(b"t", timeout=1)
- except:
- clientsocket, address = serversocket.accept()
- elif data == b'exit':
- self.endstate = True
- self.quit = True
- else:
- if type(data) != type("str"):
- data = data.decode()
- if data[0:3] == "Log":
- self.log_input(data)
- elif data[0:5] == "Error":
- self.error_state = True
- self.log_input(data)
- if self.endstate == False:
- self.log_input("Program exited without sending quit.")
- estate = ctypes.windll.user32.MessageBoxW(None, 'The Application closed unexpectedly.\nWould you like to send a log?', 'App Error', 1)
- if estate == 1:
- with open(self.tmpdir+self.file, "w+") as f:
- f.write("\r\n".join(self.log))
- self.send_mail(self.tmpdir+self.file)
- os.remove(self.tmpdir+self.file)
- elif self.error_state == True:
- self.log_input("Program exited but errors detected")
- try:
- clientsocket.close()
- except:
- pass
- estate = ctypes.windll.user32.MessageBoxW(None, 'Some Errors were detected.\nWould you like to send a log?', 'App Error', 1)
- if estate == 1:
- with open(self.tmpdir+self.file, "w+") as f:
- f.write("\r\n".join(self.log))
- self.send_mail(self.tmpdir+self.file)
- os.remove(self.tmpdir+self.file)
- else:
- try:
- clientsocket.close()
- except:
- pass
- def app_run(self):
- while not self.quit:
- try:
- [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if self.proc in p.info['name']][0]
- except:
- self.quit = True
- break
- time.sleep(1)
- def log_input(self, text):
- self.log.append(text)
- pass
- def send_mail(self, file, server="smtp.live.com", server_port=587):
- msg = MIMEMultipart()
- msg['From'] = self.config['from']
- msg['To'] = self.config['to']
- msg['Subject'] = "Debug Log"
- msg.attach(MIMEText("System Debug Log"))
- with open(file, "rb") as fil:
- part = MIMEApplication(fil.read(), Name=os.path.basename(file))
- part['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(file)
- msg.attach(part)
- smtp = smtplib.SMTP(server, server_port)
- smtp.ehlo()
- smtp.starttls()
- smtp.ehlo()
- smtp.login(self.config['from'], self.config['pass'])
- smtp.set_debuglevel(True)
- smtp.sendmail(msg['From'], msg['To'], msg.as_string())
- smtp.quit()
- if __name__ == "__main__":
- try:
- if len(sys.argv) == 3:
- logger = socket_logger(sys.argv[1], sys.argv[2])
- logger.starter()
- else:
- ctypes.windll.user32.MessageBoxW(None, 'The Log failed to initilise.\nFailed to create with system arguments: 1001.\nPlease Contact your Administrator', 'Logger Error', 0)
- except:
- raise
- ##Required logger.ini:
- [EMAIL]
- to = some_email
- from = hotmail_email
- pass = hotmail_password
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement