Coverage for portality/error_handler.py: 17%

46 statements  

« prev     ^ index     » next       coverage.py v6.4.2, created at 2022-07-22 15:59 +0100

1import logging 

2import logging.handlers 

3import sys 

4 

5 

6# just use GMail 

7class TlsSMTPHandler(logging.handlers.SMTPHandler): 

8 def emit(self, record): 

9 """ 

10 Emit a record. 

11  

12 Format the record and send it to the specified addressees. 

13 """ 

14 try: 

15 import smtplib 

16 import string # for tls add this line 

17 try: 

18 from email.utils import formatdate 

19 except ImportError: 

20 formatdate = self.date_time 

21 port = self.mailport 

22 if not port: 

23 port = smtplib.SMTP_PORT 

24 smtp = smtplib.SMTP(self.mailhost, port) 

25 msg = self.format(record) 

26 msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( 

27 self.fromaddr, 

28 self.toaddrs + ",", 

29 self.getSubject(record), 

30 formatdate(), msg) 

31 if self.username: 

32 smtp.ehlo() # for tls add this line 

33 smtp.starttls() # for tls add this line 

34 smtp.ehlo() # for tls add this line 

35 smtp.login(self.username, self.password) 

36 smtp.sendmail(self.fromaddr, self.toaddrs, msg) 

37 smtp.quit() 

38 except (KeyboardInterrupt, SystemExit): 

39 raise 

40 except: 

41 self.handleError(record) 

42 

43 

44def setup_error_logging(app): 

45 """ 

46 ~~ErrorHandler:Feature->Logging:Library~~ 

47 ~~->Email:ExternalService~~ 

48 :param app: 

49 :return: 

50 """ 

51 # Custom logging WILL BE IGNORED by Flask if app.debug == True - 

52 # even if you remove the condition below. 

53 if app.debug: 

54 return 

55 

56 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 

57 

58 send_to = app.config.get('ERROR_LOGGING_EMAIL', app.config.get('ADMIN_EMAIL')) 

59 if send_to and not app.config.get('SUPPRESS_ERROR_EMAILS'): 

60 if 'ERROR_MAIL_USERNAME' in app.config and 'ERROR_MAIL_PASSWORD' in app.config and 'ERROR_MAIL_HOSTNAME' in app.config: 

61 import platform 

62 hostname = platform.uname()[1] 

63 

64 # We have to duplicate our email config here as we can't import app_email at this point 

65 mail_handler = TlsSMTPHandler( 

66 (app.config['ERROR_MAIL_HOSTNAME'], 587), 

67 'server-error@' + hostname, 

68 send_to, 

69 'DOAJ Flask Error', 

70 credentials=(app.config['ERROR_MAIL_USERNAME'], app.config['ERROR_MAIL_PASSWORD']) 

71 ) 

72 mail_handler.setLevel(logging.ERROR) 

73 mail_handler.setFormatter(formatter) 

74 app.logger.addHandler(mail_handler) 

75 

76 # send errors to stderr, supervisord will capture them in the app's 

77 # error log 

78 send_errors_to_supervisor = logging.StreamHandler(sys.stderr) 

79 send_errors_to_supervisor.setLevel(logging.ERROR) 

80 send_errors_to_supervisor.setFormatter(formatter) 

81 app.logger.addHandler(send_errors_to_supervisor)