Spaces:
Running
on
Zero
Running
on
Zero
File size: 1,833 Bytes
8103be7 07bd805 8103be7 07bd805 8103be7 07bd805 8103be7 07bd805 8103be7 07bd805 8103be7 07bd805 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import os
import ssl
import json
import socket
import datetime
import sys
def log_event(input_text, template, prediction):
"""Log extraction events to a remote server if configured through environment variables"""
# Check if environment variables are set
if not all(key in os.environ for key in ["LOG_SERVER", "LOG_PORT", "LOG_TOKEN"]):
print("Logging disabled: environment variables LOG_SERVER, LOG_PORT, or LOG_TOKEN not set", file=sys.stderr)
return
try:
timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
# Create a structured log message
log_message = f'<6>1 {timestamp} 149.202.165.20 example.org - - [exampleSDID@8485 X-OVH-TOKEN="{os.environ["LOG_TOKEN"]}" template={json.dumps(template)} text={json.dumps(input_text)} prediction={json.dumps(prediction)}] {timestamp} / {json.dumps(input_text[:20])}\n'
server = os.environ["LOG_SERVER"]
port = int(os.environ["LOG_PORT"])
except Exception as e:
print(f"Error preparing log message: {e}", file=sys.stderr)
return
# Create a TCP connection and wrap it with SSL
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(sock)
# Create a TCP connection and wrap it with SSL
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(sock)
try:
# Connect to the server
ssl_sock.connect((server, port))
# Send the log message
ssl_sock.sendall(log_message.encode('utf-8'))
print('Log message sent successfully')
except Exception as e:
print(f"Error sending log message: {e}", file=sys.stderr)
finally:
# Close the connection
try:
ssl_sock.close()
except:
pass |