import logging
import os
import json
from datetime import datetime
class SandboxLogger:
def __init__(self, log_file="sandbox.log"):
self.log_file = log_file
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.INFO) # Set default logging level
# Create a handler to write logs to the file
self.file_handler = logging.FileHandler(self.log_file)
self.formatter = logging.Formatter('%(message)s') # Simple message format
self.file_handler.setFormatter(self.formatter)
self.logger.addHandler(self.file_handler)
def log_entry(self, message, level="INFO", data=None):
"""
Logs an entry to the sandbox log file.
Args:
message (str): The log message.
level (str): The log level (e.g., "DEBUG", "INFO", "WARNING", "ERROR"). Defaults to "INFO".
data (dict, optional): Additional data to include in the log entry. Defaults to None.
"""
try:
log_data = {
"timestamp": datetime.now().isoformat(),
"level": level,
"message": message,
"data": data
}
# Log to file
self.logger.info(json.dumps(log_data))
except Exception as e:
self.logger.error(f"Error logging entry: {e}")
def clear_log(self):
"""
Clears the log file.
"""
try:
open(self.log_file, 'w').close()
except Exception as e:
self.logger.error(f"Error clearing log file: {e}")
def get_log_content(self):
"""
Returns the entire log file content as a string.
"""
try:
with open(self.log_file, 'r') as f:
return f.read()
except FileNotFoundError:
return "Log file not found."
except Exception as e:
return f"Error reading log file: {e}"
def check_log_file_exists(self):
"""
Checks if the log file exists. Returns True if it exists, False otherwise.
"""
return os.path.exists(self.log_file)
Add your comment