diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..298ea9e --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,19 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..d734c75 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,57 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +import os +import sys +sys.path.insert(0, os.path.abspath('.')) + +# -- Project information ----------------------------------------------------- + +project = 'django_logging' +copyright = '2024, django_logging' +author = 'ARYAN NIKNEZHAD, MEHRSHAD-MIRSHEKARY' + +# The full version, including alpha/beta/rc tags +release = '1.0.0' + +master_doc = 'index' + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', # Auto-generate API documentation + 'sphinx.ext.napoleon', # Support for NumPy and Google style docstrings + 'sphinx.ext.viewcode', # Add links to highlighted source code + 'sphinx.ext.githubpages' # Publish documentation on GitHub Pages +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "sphinx_rtd_theme" + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Custom static files +html_logo = '_static/logo.png' +html_favicon = '_static/favicon.ico' diff --git a/docs/contributing.rst b/docs/contributing.rst new file mode 100644 index 0000000..851e6ee --- /dev/null +++ b/docs/contributing.rst @@ -0,0 +1,159 @@ +Contributing to django_logging +============================== + +We’re excited that you’re interested in contributing to `django_logging`! Whether you’re fixing a bug, adding a feature, or improving the project, your help is appreciated. + +Overview +-------- + +- **Setting Up Your Environment** +- **Testing Your Changes** +- **Code Style Guidelines** +- **Utilizing Pre-commit Hooks** +- **Creating a Pull Request** +- **Reporting Issues** +- **Resources** + +Setting Up Your Environment +--------------------------- + +1. **Fork the Repository:** + + Begin by forking the `django_logging` repository on GitHub. This creates your own copy where you can make changes. + +2. **Clone Your Fork:** + + Use the following command to clone your fork locally: + + .. code-block:: bash + + git clone https://github.com/your-username/django_logging.git + cd django_logging + +3. **Install Dependencies:** + + Install the necessary dependencies using `Poetry`. If Poetry isn't installed on your machine, you can find installation instructions on the `Poetry website `_. + + .. code-block:: bash + + poetry install + +4. **Create a Feature Branch:** + + It’s a good practice to create a new branch for your work: + + .. code-block:: bash + + git checkout -b feature/your-feature-name + +Testing Your Changes +-------------------- + +We use `pytest` for running tests. Before submitting your changes, ensure that all tests pass: + +.. code-block:: bash + + poetry run pytest + +If you’re adding a new feature or fixing a bug, don’t forget to write tests to cover your changes. + +Code Style Guidelines +---------------------- + +Maintaining a consistent code style is crucial. We use `black` for code formatting and `isort` for import sorting. Make sure your code adheres to these styles: + +.. code-block:: bash + + poetry run black . + poetry run isort . + +For linting, `pylint` is used to enforce style and catch potential errors: + +.. code-block:: bash + + poetry run pylint django_logging + +Utilizing Pre-commit Hooks +-------------------------- + +Pre-commit hooks are used to automatically check and format code before you make a commit. This ensures consistency and quality in the codebase. + +1. **Install Pre-commit:** + + .. code-block:: bash + + poetry add --dev pre-commit + +2. **Set Up the Hooks:** + + Install the pre-commit hooks by running: + + .. code-block:: bash + + poetry run pre-commit install + +3. **Manual Hook Execution (Optional):** + + To run all hooks manually on your codebase: + + .. code-block:: bash + + poetry run pre-commit run --all-files + +Creating a Pull Request +----------------------- + +Once your changes are ready, follow these steps to submit them: + +1. **Commit Your Changes:** + + Write clear and concise commit messages. Following the `Conventional Commits `_ format is recommended: + + .. code-block:: bash + + git commit -am 'feat: add custom logging formatter' + +2. **Push Your Branch:** + + Push your branch to your fork on GitHub: + + .. code-block:: bash + + git push origin feature/your-feature-name + +3. **Open a Pull Request:** + + Go to the original `django_logging` repository and open a pull request. Include a detailed description of your changes and link any related issues. + +4. **Respond to Feedback:** + + After submitting, a maintainer will review your pull request. Be prepared to make revisions based on their feedback. + +Reporting Issues +---------------- + +Found a bug or have a feature request? We’d love to hear from you! + +1. **Open an Issue:** + + Head over to the `Issues` section of the `django_logging` repository and click "New Issue". + +2. **Describe the Problem:** + + Fill out the issue template with as much detail as possible. This helps us understand and address the issue more effectively. + +Resources +--------- + +Here are some additional resources that might be helpful: + +- `Poetry Documentation `_ +- `Black Documentation `_ +- `isort Documentation `_ +- `pytest Documentation `_ +- `pylint Documentation `_ +- `Pre-commit Documentation `_ + +--- + +Thank you for your interest in contributing to `django_logging`! We look forward to your contributions. diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..1e8d2f8 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,67 @@ +Welcome to django_logging Documentation! +======================================== + +.. |br| raw:: html + +
+ +.. image:: https://img.shields.io/pypi/v/django_logging + :target: https://pypi.org/project/django_logging/ + :alt: PyPI release + +.. image:: https://img.shields.io/pypi/pyversions/django_logging + :target: https://pypi.org/project/django_logging/ + :alt: Supported Python versions + +.. image:: https://img.shields.io/pypi/djversions/django_logging + :target: https://pypi.org/project/django_logging/ + :alt: Supported Django versions + +.. image:: https://img.shields.io/readthedocs/django_logging + :target: https://django_logging.readthedocs.io/ + :alt: Documentation + +|br| + +`django_logging` is a Django package designed to extend and enhance Python’s built-in logging capabilities. By providing customizable configurations and advanced features, it offers developers a comprehensive logging solution tailored specifically for Django applications. + +Supported Versions +------------------ + +`django_logging` supports the following combinations of Django and Python versions: + +========== ======================= + Django Python +========== ======================= +4.2 3.8, 3.9, 3.10, 3.11, 3.12 +5.0 3.10, 3.11, 3.12 +5.1 3.10, 3.11, 3.12 +========== ======================= + +Documentation +------------- + +The documentation is organized into the following sections: + +.. toctree:: + :maxdepth: 2 + + quick_start + usage + settings + contributing + rules + +Issues +------ +If you have questions or have trouble using the app please file a bug report at: + +https://github.com/ARYAN-NIKNEZHAD/django_logging + + +Indices and tables +================== + +* :ref:`search` +* :ref:`genindex` +* :ref:`modindex` \ No newline at end of file diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..f089095 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% + +:end +popd \ No newline at end of file diff --git a/docs/quick_start.rst b/docs/quick_start.rst new file mode 100644 index 0000000..ae7f0cc --- /dev/null +++ b/docs/quick_start.rst @@ -0,0 +1,51 @@ +Quick Start +=========== + +Getting Started with `django_logging` is simple. Follow these steps to get up and running quickly: + +1. **Installation** + + Install `django_logging` via pip: + + .. code-block:: shell + + $ pip install django_logging + +2. **Add to Installed Apps** + + Add `django_logging` to your `INSTALLED_APPS` in your Django settings file: + + .. code-block:: python + + INSTALLED_APPS = [ + ... + 'django_logging', + ... + ] + +3. **Default Configuration** + + By default, `django_logging` is configured to use its built-in settings. You do not need to configure anything manually unless you want to customize the behavior. The default settings will automatically handle logging with predefined formats and options. + +4. **Verify Installation** + + To ensure everything is set up correctly, run your Django development server: + + .. code-block:: shell + + python manage.py runserver + + By default, `django_logging` will log an initialization message to the console that looks like this: + + .. code-block:: text + + INFO | django_logging | Logging initialized with the following configurations: + Log File levels: ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']. + Log files are being written to: logs. + Console output level: DEBUG. + Colorize console: True. + Log date format: %Y-%m-%d %H:%M:%S. + Email notifier enabled: False. + + +That's it! `django_logging` is ready to use with default settings. For further customization, refer to the [Settings](settings.rst) section. \ No newline at end of file diff --git a/docs/rules.rst b/docs/rules.rst new file mode 100644 index 0000000..22f03a5 --- /dev/null +++ b/docs/rules.rst @@ -0,0 +1,80 @@ +Roles +===== + +The `django_logging` package provides several logging roles to cater to different logging needs and contexts. These roles define specific behaviors and configurations, making it easier to manage logging in a Django application. + +Available Roles +--------------- + +1. **Basic Logger Role** + + The Basic Logger Role is designed for standard logging use cases. It handles logging messages of different severity levels (DEBUG, INFO, WARNING, ERROR, CRITICAL) and outputs them to both the console and log files, depending on the settings. + + **Key Features:** + - Supports all standard logging levels. + - Configurable to write logs to a file, the console, or both. + - Can be integrated easily across different modules in your Django project. + +2. **Request Logging Role** + + The Request Logging Role is specifically designed to log HTTP request details. This role captures information such as the request path, user, IP address, and user agent. + + **Key Features:** + - Logs details of incoming requests. + - Can be customized to include additional request metadata. + - Useful for monitoring and debugging purposes. + + **Example Configuration:** + + .. code-block:: python + + MIDDLEWARE = [ + ... + 'django_logging.middleware.RequestLogMiddleware', + ... + ] + +3. **Email Notifier Role** + + The Email Notifier Role enables sending logs via email. This is particularly useful for critical errors that require immediate attention. + + **Key Features:** + - Sends log messages via email to designated recipients. + - Supports customizable log levels for triggering email notifications. + - Requires proper email configuration in the Django settings. + + **Example Usage:** + + .. code-block:: python + + from django_logging.utils.log_email_notifier.log_and_notify import log_and_notify_admin + import logging + + logger = logging.getLogger(__name__) + + log_and_notify_admin(logger, logging.CRITICAL, "Critical error occurred!") + + **Note:** To use this role, ensure that `LOG_EMAIL_NOTIFIER` is enabled and properly configured. + +4. **Context Manager Role** + + The Context Manager Role provides a way to temporarily apply different logging configurations within a specific block of code. This is useful when you need to adjust logging behavior for certain operations without affecting the global configuration. + + **Key Features:** + - Allows temporary configuration changes within a context. + - Automatically reverts to the original configuration after exiting the context. + - Useful for testing or handling specific scenarios where different logging behavior is required. + + **Example Usage:** + + .. code-block:: python + + from django_logging.utils.context_manager import config_setup + import logging + + logger = logging.getLogger(__name__) + + with config_setup(): + logger.info("This log uses temporary configurations") + + diff --git a/docs/settings.rst b/docs/settings.rst new file mode 100644 index 0000000..e5c4054 --- /dev/null +++ b/docs/settings.rst @@ -0,0 +1,119 @@ +Settings +======== + +The `DJANGO_LOGGING` configuration allows you to customize various aspects of logging within your Django project. Below is a detailed description of each configurable option. + +Configuration Options +---------------------- + +The settings are defined in the `DJANGO_LOGGING` dictionary in your `settings.py` file. Here’s a breakdown of each option: + + + +By default, `django_logging` uses a built-in configuration that requires no additional setup. However, you can customize the logging settings by adding a `DJANGO_LOGGING` configuration to your Django settings file. + +Example configuration: + + .. code-block:: python + + DJANGO_LOGGING = { + "AUTO_INITIALIZATION_ENABLE": True, + "INITIALIZATION_MESSAGE_ENABLE": True, + "LOG_FILE_LEVELS": ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], + "LOG_DIR": "logs", + "LOG_FILE_FORMATS": { + "DEBUG": 1, + "INFO": 1, + "WARNING": 1, + "ERROR": 1, + "CRITICAL": 1, + }, + "LOG_CONSOLE_LEVEL": "DEBUG", + "LOG_CONSOLE_FORMAT": 1, + "LOG_CONSOLE_COLORIZE": True, + "LOG_DATE_FORMAT": "%Y-%m-%d %H:%M:%S", + "LOG_EMAIL_NOTIFIER": { + "ENABLE": False, + "NOTIFY_ERROR": False, + "NOTIFY_CRITICAL": False, + "LOG_FORMAT": 1, + "USE_TEMPLATE": True + } + } + + +Here's a breakdown of the available configuration options: + +- **AUTO_INITIALIZATION_ENABLE**: Accepts `bool`. Enables automatic initialization of logging configurations. Defaults to `True`. +- **INITIALIZATION_MESSAGE_ENABLE**: Accepts `bool`. Enables logging of the initialization message. Defaults to `True`. +- **LOG_FILE_LEVELS**: Accepts a list of valid log levels (a list of `str` where each value must be one of the valid levels). Defines the log levels for file logging. Defaults to `['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']`. +- **LOG_DIR**: Accepts `str` like `"path/to/logs"` or a path using functions like `os.path.join()`. Specifies the directory where log files will be stored. Defaults to `"logs"`. +- **LOG_FILE_FORMATS**: Accepts log levels as keys and format options as values. The format option can be an `int` chosen from predefined options or a user-defined format `str`. Defines the format for log files. Defaults to `1` for all levels. + - **Note**:See the **Available Format Options** below for available formats. +- **LOG_CONSOLE_LEVEL**: Accepts `str` that is a valid log level. Specifies the log level for console output. Defaults to `'DEBUG'`, +- **LOG_CONSOLE_FORMAT**: Accepts the same options as `LOG_FILE_FORMATS`. Defines the format for console output. Defaults to `1`. +- **LOG_CONSOLE_COLORIZE**: Accepts `bool`. Determines whether to colorize console output. Defaults to `True`. +- **LOG_DATE_FORMAT**: Accepts `str` that is a valid datetime format. Specifies the date format for log messages. Defaults to `'%Y-%m-%d %H:%M:%S'`. +- **LOG_EMAIL_NOTIFIER**: Is a dictionary where: + - **ENABLE**: Accepts `bool`. Determines whether the email notifier is enabled. Defaults to `False`. + - **NOTIFY_ERROR**: Accepts `bool`. Determines whether to notify on error logs. Defaults to `False`. + - **NOTIFY_CRITICAL**: Accepts `bool`. Determines whether to notify on critical logs. Defaults to `False`. + - **LOG_FORMAT**: Accepts the same options as other log formats (`int` or `str`). Defines the format for log messages sent via email. Defaults to `1`. + - **USE_TEMPLATE**: Accepts `bool`. Determines whether the email includes an HTML template. Defaults to `True`. + + +Available Format Options +========================= + +The `django_logging` package provides predefined log format options that you can use in configuration. These options can be applied to log formats. Below are the available format options: + +.. code-block:: python + + FORMAT_OPTIONS = { + 1: "%(levelname)s | %(asctime)s | %(module)s | %(message)s", + 2: "%(levelname)s | %(asctime)s | %(message)s", + 3: "%(levelname)s | %(message)s", + 4: "%(asctime)s - %(name)s - %(levelname)s - %(message)s", + 5: "%(levelname)s | %(message)s | [in %(pathname)s:%(lineno)d]", + 6: "%(asctime)s | %(levelname)s | %(message)s", + 7: "%(levelname)s | %(asctime)s | in %(module)s: %(message)s", + 8: "%(levelname)s | %(message)s | [%(filename)s:%(lineno)d]", + 9: "[%(asctime)s] | %(levelname)s | in %(module)s: %(message)s", + 10: "%(asctime)s | %(processName)s | %(name)s | %(levelname)s | %(message)s", + 11: "%(asctime)s | %(threadName)s | %(name)s | %(levelname)s | %(message)s", + 12: "%(levelname)s | [%(asctime)s] | (%(filename)s:%(lineno)d) | %(message)s", + 13: "%(levelname)s | [%(asctime)s] | {%(name)s} | (%(filename)s:%(lineno)d): %(message)s", + } + +You can reference these formats by their corresponding integer keys in your logging configuration settings. + + +Required Email Settings +----------------------- + +To use the email notifier, the following email settings must be configured in your `settings.py`: + +- **`EMAIL_HOST`**: The host to use for sending emails. +- **`EMAIL_PORT`**: The port to use for the email server. +- **`EMAIL_HOST_USER`**: The username to use for the email server. +- **`EMAIL_HOST_PASSWORD`**: The password to use for the email server. +- **`EMAIL_USE_TLS`**: Whether to use a TLS (secure) connection when talking to the email server. +- **`DEFAULT_FROM_EMAIL`**: The default email address to use for sending emails. +- **`ADMIN_EMAIL`**: The email address where log notifications will be sent. This is the recipient address used by the email notifier to deliver the logs. + +Example Email Settings +---------------------- + +Below is an example configuration for the email settings in your `settings.py`: + +.. code-block:: python + + EMAIL_HOST = 'smtp.example.com' + EMAIL_PORT = 587 + EMAIL_HOST_USER = 'your-email@example.com' + EMAIL_HOST_PASSWORD = 'your-password' + EMAIL_USE_TLS = True + DEFAULT_FROM_EMAIL = 'your-email@example.com' + ADMIN_EMAIL = 'admin@example.com' + +These settings ensure that the email notifier is correctly configured to send log notifications to the specified `ADMIN_EMAIL` address. diff --git a/docs/usage.rst b/docs/usage.rst new file mode 100644 index 0000000..6baf5aa --- /dev/null +++ b/docs/usage.rst @@ -0,0 +1,119 @@ +Usage +===== + +Once `django_logging` is installed and added to your `INSTALLED_APPS`, you can start using it right away. The package provides several features to customize and enhance logging in your Django project. Below is a guide on how to use the various features provided by `django_logging`. + +1. **Basic Logging Usage** + + At its core, `django_logging` is built on top of Python’s built-in logging module. This means you can use the standard logging module to log messages across your Django project. Here’s a basic example of logging usage: + + .. code-block:: python + + import logging + + logger = logging.getLogger(__name__) + + logger.debug("This is a debug message") + logger.info("This is an info message") + logger.warning("This is a warning message") + logger.error("This is an error message") + logger.critical("This is a critical message") + + These logs will be handled according to the configurations set up by `django_logging`, using either the default settings or any custom settings you've provided. + +2. **Request Logging Middleware** + + To log request information such as the request path, user, IP address, and user agent, add `django_logging.middleware.RequestLogMiddleware` to your `MIDDLEWARE` setting: + + .. code-block:: python + + MIDDLEWARE = [ + ... + 'django_logging.middleware.RequestLogMiddleware', + ... + ] + + This middleware will log request details at info level, here is an example with default format: + + .. code-block:: text + + INFO | 'datetime' | django_logging | Request Info: (request_path: /example-path, user: example_user, + IP: 192.168.1.1, user_agent: Mozilla/5.0) + +3. **Context Manager** + + You can use the `config_setup` context manager to temporarily apply `django_logging` configurations within a specific block of code. + + Example usage: + + .. code-block:: python + + from django_logging.utils.context_manager import config_setup + import logging + + logger = logging.getLogger(__name__) + + def foo(): + logger.info("This log will use the configuration set in the context manager!") + + with config_setup(): + """ Your logging configuration changes here""" + foo() + + + Note: `AUTO_INITIALIZATION_ENABLE` must be set to `False` in the settings to use the context manager. If `AUTO_INITIALIZATION_ENABLE` is `True`, attempting to use the context manager will raise a `ValueError` with the message: + + .. code-block:: text + + "You must set 'AUTO_INITIALIZATION_ENABLE' to False in DJANGO_LOGGING in your settings to use the context manager." + +4. **Log and Notify Utility** + + To send specific logs as email, use the `log_and_notify_admin` function. Ensure that the `ENABLE` option in `LOG_EMAIL_NOTIFIER` is sent to `True` in your settings: + + .. code-block:: python + + from django_logging.utils.log_email_notifier.log_and_notify import log_and_notify_admin + import logging + + logger = logging.getLogger(__name__) + + log_and_notify_admin(logger, logging.INFO, "This is a log message") + + You can also include additional request information in the email by passing an `extra` dictionary: + + .. code-block:: python + + from django_logging.utils.log_email_notifier.log_and_notify import log_and_notify_admin + import logging + + logger = logging.getLogger(__name__) + + def some_view(request): + log_and_notify_admin( + logger, + logging.INFO, + "This is a log message", + extra={"request": request} + ) + + Note: To use the email notifier, `LOG_EMAIL_NOTIFIER["ENABLE"]` must be set to `True`. If it is not enabled, calling `log_and_notify_admin` will raise a `ValueError`: + + .. code-block:: text + + "Email notifier is disabled. Please set the 'ENABLE' option to True in the 'LOG_EMAIL_NOTIFIER' in DJANGO_LOGGING in your settings to activate email notifications." + + Additionally, ensure that all required email settings are configured in your Django settings file. + - **Note**: For more detailed configuration options, refer to the [Settings](settings.rst) section. + +5. **Send Logs Command** + + To send the entire log directory to a specified email address, use the `send_logs` management command: + + .. code-block:: shell + + python manage.py send_logs example@domain.com + + This command will attach the log directory and send a zip file to the provided email address. + +