-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
✨💡 feat(commands): add send_logs Command to send logs dir
Implemented a Django Management Command to Send Logs Directory via Email: Dynamic Log Directory Path: gets log directory path dynamically from the DJANGO_LOGGING settings, allowing for user-defined paths. Zip Log Directory: Added functionality to compress the log directory into a zip file. Email with Attachment: Created and sent an email to a specified address with the zipped log files as an attachment. Error Handling: Included error handling for cases where the log directory does not exist or email sending fails. Temporary File Management: Ensured temporary files are cleaned up after use. Email Settings Validation: Added a check to ensure all required email settings are present in the Django settings. Closes #10
- Loading branch information
1 parent
4edf3ce
commit 64b60d8
Showing
3 changed files
with
107 additions
and
0 deletions.
There are no files selected for viewing
Empty file.
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) |