diff --git a/django_logging/management/__init__.py b/django_logging/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/django_logging/management/commands/__init__.py b/django_logging/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/django_logging/management/commands/send_logs.py b/django_logging/management/commands/send_logs.py new file mode 100644 index 0000000..e7fd085 --- /dev/null +++ b/django_logging/management/commands/send_logs.py @@ -0,0 +1,107 @@ +import os +import shutil +import tempfile +import logging +from django.core.mail import EmailMessage +from django.core.management.base import BaseCommand +from django.conf import settings + +logger = logging.getLogger(__name__) + + +class Command(BaseCommand): + """ + A Django management command that zips the log directory and sends it to + the specified email address. + + This command is used to send the log files to a specified email address. + It zips the log directory, creates an email with the zipped file as an attachment, + and sends it to the specified email address. + """ + + help = "Send log folder to the specified email address" + + def add_arguments(self, parser): + """ + Add custom command arguments. + + Parameters: + parser (ArgumentParser): The argument parser to add arguments to. + """ + parser.add_argument( + "email", type=str, help="The email address to send the logs to" + ) + + def handle(self, *args, **kwargs): + """ + The main entry point for the command. + + Parameters: + args (tuple): Positional arguments. + kwargs (dict): Keyword arguments. + """ + email = kwargs["email"] + + log_dir = settings.DJANGO_LOGGING.get("LOG_DIR", os.path.join(os.getcwd(), "logs")) + + if not os.path.exists(log_dir): + self.stdout.write( + self.style.ERROR(f'Log directory "{log_dir}" does not exist.') + ) + logger.error(f'Log directory "{log_dir}" does not exist.') + return + + self.check_email_settings() + + # Create a temporary file to store the zipped logs + with tempfile.NamedTemporaryFile(delete=False) as tmp_file: + zip_path = f"{tmp_file.name}.zip" + tmp_file.close() + + # Zip the log directory + shutil.make_archive(tmp_file.name, "zip", log_dir) + + # Send the email with the zipped logs + email_subject = "Log Files" + email_body = "Please find the attached log files." + email_message = EmailMessage( + subject=email_subject, + body=email_body, + from_email=settings.DEFAULT_FROM_EMAIL, + to=[email], + ) + email_message.attach_file(zip_path) + + try: + email_message.send() + self.stdout.write(self.style.SUCCESS(f"Logs sent successfully to {email}.")) + logger.info(f"Logs sent successfully to {email}.") + except Exception as e: + self.stdout.write(self.style.ERROR(f"Failed to send logs: {e}")) + logger.error(f"Failed to send logs: {e}") + finally: + # Clean up the temporary file + os.remove(zip_path) + logger.info("Temporary zip file cleaned up successfully.") + + def check_email_settings(self): + """ + Check if all required email settings are present in the settings file. + + Raises an exception if any of the required email settings are missing. + """ + required_settings = [ + "EMAIL_HOST", + "EMAIL_PORT", + "EMAIL_HOST_USER", + "EMAIL_HOST_PASSWORD", + "EMAIL_USE_TLS", + "DEFAULT_FROM_EMAIL", + ] + + for setting in required_settings: + if not getattr(settings, setting, None): + error_message = f"Missing required email setting: {setting}" + self.stdout.write(self.style.ERROR(error_message)) + logger.error(f"Missing required email setting: {setting}") + raise Exception(error_message)