|
4 | 4 | from email.parser import Parser |
5 | 5 | import os |
6 | 6 | import base64 |
| 7 | +import logging |
| 8 | + |
| 9 | +# Configure logging |
| 10 | +logging.basicConfig( |
| 11 | + level=logging.INFO, |
| 12 | + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' |
| 13 | +) |
| 14 | +logger = logging.getLogger(__name__) |
7 | 15 |
|
8 | 16 | EMAIL_FROM = os. getenv( "EMAIL_FROM", "[email protected]") |
9 | 17 | |
@@ -44,17 +52,27 @@ def webhook(): |
44 | 52 | payload = email_message.get_payload(decode=True) |
45 | 53 |
|
46 | 54 | if payload is None: |
47 | | - raise ValueError("The email body is missing or not decodable") |
| 55 | + error_msg = "The email body is missing or not decodable" |
| 56 | + logger.error(f"400 Bad Request - {error_msg} - Request from {request.remote_addr} - Content-Type: {request.content_type}") |
| 57 | + raise ValueError(error_msg) |
48 | 58 |
|
49 | 59 | message_content = payload.decode('utf-8') |
50 | 60 | if len(message_content) < 10: |
51 | | - raise ValueError("The email body must have at least 10 characters") |
| 61 | + error_msg = "The email body must have at least 10 characters" |
| 62 | + logger.error(f"400 Bad Request - {error_msg} - Request from {request.remote_addr} - Body length: {len(message_content)}") |
| 63 | + raise ValueError(error_msg) |
52 | 64 |
|
53 | 65 | send_email(message_content, original_infos) |
54 | 66 | return "OK", 200 |
55 | 67 | except (KeyError, ValueError, base64.binascii.Error) as e: |
| 68 | + try: |
| 69 | + data_info = f"Data keys: {list(request.json.keys())}" if request.json else "No JSON data" |
| 70 | + except: |
| 71 | + data_info = "Unable to parse request data" |
| 72 | + logger.error(f"400 Bad Request - {type(e).__name__}: {str(e)} - Request from {request.remote_addr} - Content-Type: {request.content_type} - {data_info}") |
56 | 73 | return jsonify({"error": str(e)}), 400 |
57 | 74 | except Exception as e: |
| 75 | + logger.exception(f"500 Internal Server Error - {type(e).__name__}: {str(e)} - Request from {request.remote_addr}") |
58 | 76 | return jsonify({"error": str(e)}), 500 |
59 | 77 |
|
60 | 78 | def format_forwarded_email_header(original_infos): |
|
0 commit comments