dj-logging 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. dj_logging-1.0.0/AUTHORS.md +10 -0
  2. dj_logging-1.0.0/LICENCE +21 -0
  3. dj_logging-1.0.0/PKG-INFO +331 -0
  4. dj_logging-1.0.0/README.md +294 -0
  5. dj_logging-1.0.0/django_logging/__init__.py +0 -0
  6. dj_logging-1.0.0/django_logging/apps.py +32 -0
  7. dj_logging-1.0.0/django_logging/constants/__init__.py +4 -0
  8. dj_logging-1.0.0/django_logging/constants/ansi_colors.py +42 -0
  9. dj_logging-1.0.0/django_logging/constants/config_types.py +27 -0
  10. dj_logging-1.0.0/django_logging/constants/date_format_directives.py +22 -0
  11. dj_logging-1.0.0/django_logging/constants/default_settings.py +56 -0
  12. dj_logging-1.0.0/django_logging/constants/log_format_options.py +15 -0
  13. dj_logging-1.0.0/django_logging/constants/log_format_specifiers.py +18 -0
  14. dj_logging-1.0.0/django_logging/constants/required_email_settings.py +10 -0
  15. dj_logging-1.0.0/django_logging/filters/__init__.py +1 -0
  16. dj_logging-1.0.0/django_logging/filters/log_level_filter.py +38 -0
  17. dj_logging-1.0.0/django_logging/formatters/__init__.py +1 -0
  18. dj_logging-1.0.0/django_logging/formatters/colored_formatter.py +21 -0
  19. dj_logging-1.0.0/django_logging/handlers/__init__.py +1 -0
  20. dj_logging-1.0.0/django_logging/handlers/email_handler.py +55 -0
  21. dj_logging-1.0.0/django_logging/management/__init__.py +0 -0
  22. dj_logging-1.0.0/django_logging/management/commands/__init__.py +0 -0
  23. dj_logging-1.0.0/django_logging/management/commands/send_logs.py +111 -0
  24. dj_logging-1.0.0/django_logging/middleware/__init__.py +1 -0
  25. dj_logging-1.0.0/django_logging/middleware/request_middleware.py +84 -0
  26. dj_logging-1.0.0/django_logging/settings/__init__.py +0 -0
  27. dj_logging-1.0.0/django_logging/settings/checks.py +155 -0
  28. dj_logging-1.0.0/django_logging/settings/conf.py +219 -0
  29. dj_logging-1.0.0/django_logging/templates/email_notifier_template.html +48 -0
  30. dj_logging-1.0.0/django_logging/tests/__init__.py +0 -0
  31. dj_logging-1.0.0/django_logging/tests/commands/__init__.py +0 -0
  32. dj_logging-1.0.0/django_logging/tests/commands/test_send_logs.py +212 -0
  33. dj_logging-1.0.0/django_logging/tests/conftest.py +22 -0
  34. dj_logging-1.0.0/django_logging/tests/constants.py +2 -0
  35. dj_logging-1.0.0/django_logging/tests/filters/__init__.py +0 -0
  36. dj_logging-1.0.0/django_logging/tests/filters/test_log_level_filter.py +77 -0
  37. dj_logging-1.0.0/django_logging/tests/fixtures/__init__.py +14 -0
  38. dj_logging-1.0.0/django_logging/tests/fixtures/colored_formatter_fixture.py +16 -0
  39. dj_logging-1.0.0/django_logging/tests/fixtures/conf_fixture.py +46 -0
  40. dj_logging-1.0.0/django_logging/tests/fixtures/email_handler_fixture.py +16 -0
  41. dj_logging-1.0.0/django_logging/tests/fixtures/email_notifier_fixture.py +66 -0
  42. dj_logging-1.0.0/django_logging/tests/fixtures/email_settings_fixture.py +28 -0
  43. dj_logging-1.0.0/django_logging/tests/fixtures/log_and_notify_fixture.py +35 -0
  44. dj_logging-1.0.0/django_logging/tests/fixtures/log_record_fixture.py +43 -0
  45. dj_logging-1.0.0/django_logging/tests/fixtures/logger_fixture.py +23 -0
  46. dj_logging-1.0.0/django_logging/tests/fixtures/request_middleware_fixture.py +55 -0
  47. dj_logging-1.0.0/django_logging/tests/fixtures/settings_fixture.py +58 -0
  48. dj_logging-1.0.0/django_logging/tests/fixtures/setup_django.py +55 -0
  49. dj_logging-1.0.0/django_logging/tests/formatters/__init__.py +0 -0
  50. dj_logging-1.0.0/django_logging/tests/formatters/test_colored_formatter.py +131 -0
  51. dj_logging-1.0.0/django_logging/tests/handlers/__init__.py +0 -0
  52. dj_logging-1.0.0/django_logging/tests/handlers/test_email_handler.py +205 -0
  53. dj_logging-1.0.0/django_logging/tests/middleware/__init__.py +0 -0
  54. dj_logging-1.0.0/django_logging/tests/middleware/test_request_middleware.py +153 -0
  55. dj_logging-1.0.0/django_logging/tests/settings/__init__.py +0 -0
  56. dj_logging-1.0.0/django_logging/tests/settings/test_checks.py +287 -0
  57. dj_logging-1.0.0/django_logging/tests/settings/test_conf.py +182 -0
  58. dj_logging-1.0.0/django_logging/tests/utils/__init__.py +0 -0
  59. dj_logging-1.0.0/django_logging/tests/utils/test_context_manager.py +170 -0
  60. dj_logging-1.0.0/django_logging/tests/utils/test_email_notifier.py +127 -0
  61. dj_logging-1.0.0/django_logging/tests/utils/test_get_conf.py +154 -0
  62. dj_logging-1.0.0/django_logging/tests/utils/test_log_and_notify.py +240 -0
  63. dj_logging-1.0.0/django_logging/tests/utils/test_set_conf.py +226 -0
  64. dj_logging-1.0.0/django_logging/tests/validators/__init__.py +0 -0
  65. dj_logging-1.0.0/django_logging/tests/validators/test_config_validators.py +381 -0
  66. dj_logging-1.0.0/django_logging/tests/validators/test_email_settings_validator.py +147 -0
  67. dj_logging-1.0.0/django_logging/utils/__init__.py +0 -0
  68. dj_logging-1.0.0/django_logging/utils/console_colorizer.py +29 -0
  69. dj_logging-1.0.0/django_logging/utils/context_manager.py +63 -0
  70. dj_logging-1.0.0/django_logging/utils/get_conf.py +117 -0
  71. dj_logging-1.0.0/django_logging/utils/log_email_notifier/__init__.py +0 -0
  72. dj_logging-1.0.0/django_logging/utils/log_email_notifier/log_and_notify.py +70 -0
  73. dj_logging-1.0.0/django_logging/utils/log_email_notifier/notifier.py +46 -0
  74. dj_logging-1.0.0/django_logging/utils/set_conf.py +137 -0
  75. dj_logging-1.0.0/django_logging/validators/__init__.py +0 -0
  76. dj_logging-1.0.0/django_logging/validators/config_validators.py +239 -0
  77. dj_logging-1.0.0/django_logging/validators/email_settings_validator.py +40 -0
  78. dj_logging-1.0.0/pyproject.toml +247 -0
@@ -0,0 +1,10 @@
1
+ ## Authors
2
+
3
+ - **Aryan Niknezhad**
4
+ - GitHub: [ARYAN-NIKNEZHAD](https://github.com/ARYAN-NIKNEZHAD)
5
+ - Email: aryan513966@gmail.com
6
+
7
+
8
+ - **Mehrshad Mirshekary**
9
+ - GitHub: [MEHRSHAD-MIRSHEKARY](https://github.com/MEHRSHAD-MIRSHEKARY)
10
+ - Email: mehrshad_mirshekary@email.com
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 django_logging
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,331 @@
1
+ Metadata-Version: 2.1
2
+ Name: dj-logging
3
+ Version: 1.0.0
4
+ Summary: A package for logging in django applications
5
+ Home-page: https://github.com/ARYAN-NIKNEZHAD/django_logging
6
+ License: MIT
7
+ Keywords: django_logging,django,logging
8
+ Author: ARYAN-NIKNEZHAD
9
+ Author-email: aryan513966@gmail.com
10
+ Requires-Python: >=3.8,<4.0
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Web Environment
13
+ Classifier: Framework :: Django
14
+ Classifier: Framework :: Django :: 4.2
15
+ Classifier: Framework :: Django :: 5.0
16
+ Classifier: Framework :: Django :: 5.1
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.8
23
+ Classifier: Programming Language :: Python :: 3.9
24
+ Classifier: Programming Language :: Python :: 3.10
25
+ Classifier: Programming Language :: Python :: 3.11
26
+ Classifier: Programming Language :: Python :: 3.12
27
+ Classifier: Programming Language :: Python :: 3 :: Only
28
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
29
+ Requires-Dist: django (>=4.2,<5.0) ; python_version >= "3.8" and python_version < "3.10"
30
+ Requires-Dist: django (>=4.2,<5.3) ; python_version >= "3.10"
31
+ Project-URL: Documentation, https://django_logging.readthedocs.io
32
+ Project-URL: Issues, https://github.com/ARYAN-NIKNEZHAD/django_logging/issues
33
+ Project-URL: Repository, https://github.com/ARYAN-NIKNEZHAD/django_logging
34
+ Project-URL: Source Code, https://github.com/ARYAN-NIKNEZHAD/django_logging
35
+ Description-Content-Type: text/markdown
36
+
37
+ # Django Logging
38
+
39
+ The [`django_logging`](https://github.com/ARYAN-NIKNEZHAD/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.
40
+
41
+ ![License](https://img.shields.io/github/license/ARYAN-NIKNEZHAD/django_logging)
42
+ ![PyPI release](https://img.shields.io/pypi/v/django_logging)
43
+ ![Supported Python versions](https://img.shields.io/pypi/pyversions/django_logging)
44
+ ![Supported Django versions](https://img.shields.io/pypi/djversions/django_logging)
45
+ ![Documentation](https://img.shields.io/readthedocs/django_logging)
46
+ ![Last Commit](https://img.shields.io/github/last-commit/ARYAN-NIKNEZHAD/django_logging)
47
+ ![Languages](https://img.shields.io/github/languages/top/ARYAN-NIKNEZHAD/django_logging)
48
+ ![CI Workflow](https://github.com/ARYAN-NIKNEZHAD/django_logging/actions/workflows/ci.yml/badge.svg)
49
+ ![Open Issues](https://img.shields.io/github/issues/ARYAN-NIKNEZHAD/django_logging)
50
+ [![codecov](https://codecov.io/gh/ARYAN-NIKNEZHAD/django_logging/branch/main/graph/badge.svg)](https://codecov.io/gh/ARYAN-NIKNEZHAD/django_logging)
51
+
52
+
53
+ ## Project Detail
54
+
55
+ - Language: Python > 3.8
56
+ - Framework: Django > 4.2
57
+
58
+
59
+ ## Documentation
60
+
61
+ The documentation is organized into the following sections:
62
+
63
+ - [Quick Start](#quick-start)
64
+ - [Usage](#usage)
65
+ - [Settings](#settings)
66
+ - [Available Format Options](#available-format-options)
67
+ - [Required Email Settings](#required-email-settings)
68
+
69
+
70
+ ## Quick Start
71
+
72
+ Getting started with `django_logging` is simple. Follow these steps to get up and running quickly:
73
+
74
+ 1. **Install the Package**
75
+
76
+ first, Install `django_logging` via pip:
77
+
78
+ ```shell
79
+ $ pip install django_logging
80
+ ```
81
+
82
+ 2. **Add to Installed Apps**
83
+
84
+ Add `django_logging` to your `INSTALLED_APPS` in your Django settings file:
85
+
86
+ ```python
87
+ INSTALLED_APPS = [
88
+ ...
89
+ 'django_logging',
90
+ ...
91
+ ]
92
+ ```
93
+
94
+
95
+ 3. **Run Your Server**
96
+
97
+ Start your Django Development server to verify the installation:
98
+ ```shell
99
+ python manage.py runserver
100
+ ```
101
+
102
+ when the server starts, you'll see an initialization message like this in your *console*:
103
+ ```shell
104
+ INFO | 'datetime' | django_logging | Logging initialized with the following configurations:
105
+ Log File levels: ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'].
106
+ Log files are being written to: logs.
107
+ Console output level: DEBUG.
108
+ Colorize console: True.
109
+ Log date format: %Y-%m-%d %H:%M:%S.
110
+ Email notifier enabled: False.
111
+ ```
112
+ By default, django_logging will log each level to its own file:
113
+ - DEBUG : `logs/debug.log`
114
+ - INFO : `logs/info.log`
115
+ - WARNING : `logs/warning.log`
116
+ - ERROR : `logs/error.log`
117
+ - CRITICAL : `logs/critical.log`
118
+
119
+ In addition, logs will be displayed in ***colorized*** mode in the `console`, making it easier to distinguish between different log levels.
120
+
121
+ That's it! `django_logging` is ready to use. For further customization, refer to the [Settings](#settings) section
122
+
123
+
124
+ ## Usage
125
+ 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`.
126
+
127
+ 1. **Basic Logging Usage**
128
+
129
+ 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:
130
+ ```python
131
+ import logging
132
+
133
+ logger = logging.getLogger(__name__)
134
+
135
+ logger.debug("This is a debug message")
136
+ logger.info("This is an info message")
137
+ logger.warning("This is a warning message")
138
+ logger.error("This is an error message")
139
+ logger.critical("This is a critical message")
140
+ ```
141
+ 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.
142
+
143
+ 2. **Request Logging Middleware**
144
+
145
+ To log the detail of each request to the server and capture information such as the request path, user, IP address, and user agent, add `django_logging.middleware.RequestLogMiddleware` to your MIDDLEWARE setting:
146
+
147
+ ```python
148
+ MIDDLEWARE = [
149
+ ...
150
+ 'django_logging.middleware.RequestLogMiddleware',
151
+ ...
152
+ ]
153
+ ```
154
+
155
+ This middleware will log th request details at info level, here is an example with default format:
156
+ ```shell
157
+ INFO | 'datetime' | django_logging | Request Info: (request_path: /example-path, user: example_user,
158
+ IP: 192.168.1.1, user_agent: Mozilla/5.0)
159
+
160
+ ```
161
+
162
+ 3. **Context Manager**
163
+
164
+ You can use the `config_setup` context manager to temporarily apply `django_logging` configurations within a specific block of code.
165
+ Example usage:
166
+ ```python
167
+ from django_logging.utils.context_manager import config_setup
168
+ import logging
169
+
170
+ logger = logging.getLogger(__name__)
171
+
172
+ def foo():
173
+ logger.info("This log will use the configuration set in the context manager!")
174
+
175
+ with config_setup():
176
+ """ Your logging configuration changes here"""
177
+ foo()
178
+
179
+ # the logging configuration will restore to what it was before, in here outside of with block
180
+ ```
181
+ - 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:
182
+ ```
183
+ "You must set 'AUTO_INITIALIZATION_ENABLE' to False in DJANGO_LOGGING in your settings to use the context manager."
184
+ ```
185
+
186
+ 4. **Log and Notify Utility**
187
+
188
+ To send specific logs as email, use the `log_and_notify_admin` function. Ensure that the `ENABLE` option in `LOG_EMAIL_NOTIFIER` is set to `True` in your settings:
189
+ ```python
190
+ from django_logging.utils.log_email_notifier.log_and_notify import log_and_notify_admin
191
+ import logging
192
+
193
+ logger = logging.getLogger(__name__)
194
+
195
+ log_and_notify_admin(logger, logging.INFO, "This is a log message")
196
+ ```
197
+ You can also include additional request information (`ip_address` and `browser_type`) in the email by passing an `extra` dictionary:
198
+ ```python
199
+ from django_logging.utils.log_email_notifier.log_and_notify import log_and_notify_admin
200
+ import logging
201
+
202
+ logger = logging.getLogger(__name__)
203
+
204
+ def some_view(request):
205
+ log_and_notify_admin(
206
+ logger,
207
+ logging.INFO,
208
+ "This is a log message",
209
+ extra={"request": request}
210
+ )
211
+ ```
212
+
213
+ - 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`:
214
+ ```shell
215
+ "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."
216
+ ```
217
+
218
+ Additionally, ensure that all [Required Email Settings](#required-email-settings) are configured in your Django settings file.
219
+
220
+ 5. **Send Logs Command**
221
+
222
+ To send the entire log directory to a specified email address, use the `send_logs` management command:
223
+ ```shell
224
+ python manage.py send_logs example@domain.com
225
+ ```
226
+ This command will attach the log directory and send a zip file to the provided email address.
227
+
228
+ ## Settings
229
+
230
+ By default, `django_logging` uses a built-in configuration that requires no additional setup. However, you can customize the logging settings by adding the `DJANGO_LOGGING` dictionary configuration to your Django `settings` file.
231
+
232
+ Example configuration:
233
+ ```python
234
+ DJANGO_LOGGING = {
235
+ "AUTO_INITIALIZATION_ENABLE": True,
236
+ "INITIALIZATION_MESSAGE_ENABLE": True,
237
+ "LOG_FILE_LEVELS": ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
238
+ "LOG_DIR": "logs",
239
+ "LOG_FILE_FORMATS": {
240
+ "DEBUG": 1,
241
+ "INFO": 1,
242
+ "WARNING": 1,
243
+ "ERROR": 1,
244
+ "CRITICAL": 1,
245
+ },
246
+ "LOG_CONSOLE_LEVEL": "DEBUG",
247
+ "LOG_CONSOLE_FORMAT": 1,
248
+ "LOG_CONSOLE_COLORIZE": True,
249
+ "LOG_DATE_FORMAT": "%Y-%m-%d %H:%M:%S",
250
+ "LOG_EMAIL_NOTIFIER": {
251
+ "ENABLE": False,
252
+ "NOTIFY_ERROR": False,
253
+ "NOTIFY_CRITICAL": False,
254
+ "LOG_FORMAT": 1,
255
+ "USE_TEMPLATE": True
256
+ }
257
+ }
258
+ ```
259
+
260
+ Here's a breakdown of the available configuration options:
261
+ - `AUTO_INITIALIZATION_ENABLE`: Accepts `bool`. Enables automatic initialization of logging configurations. Defaults to `True`.
262
+ - `INITIALIZATION_MESSAGE_ENABLE`: Accepts bool. Enables logging of the initialization message. Defaults to `True`.
263
+ - `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']`.
264
+ - `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"`.
265
+ - `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.
266
+ - **Note**: See the [Available Format Options](#available-format-options) below for available formats.
267
+ - `LOG_CONSOLE_LEVEL`: Accepts `str` that is a valid log level. Specifies the log level for console output. Defaults to `'DEBUG'`.
268
+ - `LOG_CONSOLE_FORMAT`: Accepts the same options as `LOG_FILE_FORMATS`. Defines the format for console output. Defaults to `1`.
269
+ - `LOG_CONSOLE_COLORIZE`: Accepts `bool`. Determines whether to colorize console output. Defaults to `True`.
270
+ - `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'`.
271
+ - `LOG_EMAIL_NOTIFIER`: Is a dictionary where:
272
+ - `ENABLE`: Accepts `bool`. Determines whether the email notifier is enabled. Defaults to `False`.
273
+ - `NOTIFY_ERROR`: Accepts `bool`. Determines whether to notify on error logs. Defaults to `False`.
274
+ - `NOTIFY_CRITICAL`: Accepts `bool`. Determines whether to notify on critical logs. Defaults to `False`.
275
+ - `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`.
276
+ - `USE_TEMPLATE`: Accepts `bool`. Determines whether the email includes an HTML template. Defaults to `True`.
277
+
278
+ ## Available Format Options
279
+
280
+ The `django_logging` package provides predefined log format options that you can use in configuration. Below are the available format options:
281
+
282
+ ```python
283
+ FORMAT_OPTIONS = {
284
+ 1: "%(levelname)s | %(asctime)s | %(module)s | %(message)s",
285
+ 2: "%(levelname)s | %(asctime)s | %(message)s",
286
+ 3: "%(levelname)s | %(message)s",
287
+ 4: "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
288
+ 5: "%(levelname)s | %(message)s | [in %(pathname)s:%(lineno)d]",
289
+ 6: "%(asctime)s | %(levelname)s | %(message)s",
290
+ 7: "%(levelname)s | %(asctime)s | in %(module)s: %(message)s",
291
+ 8: "%(levelname)s | %(message)s | [%(filename)s:%(lineno)d]",
292
+ 9: "[%(asctime)s] | %(levelname)s | in %(module)s: %(message)s",
293
+ 10: "%(asctime)s | %(processName)s | %(name)s | %(levelname)s | %(message)s",
294
+ 11: "%(asctime)s | %(threadName)s | %(name)s | %(levelname)s | %(message)s",
295
+ 12: "%(levelname)s | [%(asctime)s] | (%(filename)s:%(lineno)d) | %(message)s",
296
+ 13: "%(levelname)s | [%(asctime)s] | {%(name)s} | (%(filename)s:%(lineno)d): %(message)s",
297
+ }
298
+ ```
299
+
300
+ You can reference these formats by their corresponding integer keys in your logging configuration settings.
301
+
302
+ ## Required Email Settings
303
+
304
+ To use the email notifier, the following email settings must be configured in your `settings.py`:
305
+ - `EMAIL_HOST`: The host to use for sending emails.
306
+ - `EMAIL_PORT`: The port to use for the email server.
307
+ - `EMAIL_HOST_USER`: The username to use for the email server.
308
+ - `EMAIL_HOST_PASSWORD`: The password to use for the email server.
309
+ - `EMAIL_USE_TLS`: Whether to use a TLS (secure) connection when talking to the email server.
310
+ - `DEFAULT_FROM_EMAIL`: The default email address to use for sending emails.
311
+ - `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.
312
+
313
+ Example Email Settings:
314
+ ```python
315
+ EMAIL_HOST = 'smtp.example.com'
316
+ EMAIL_PORT = 587
317
+ EMAIL_HOST_USER = 'your-email@example.com'
318
+ EMAIL_HOST_PASSWORD = 'your-password'
319
+ EMAIL_USE_TLS = True
320
+ DEFAULT_FROM_EMAIL = 'your-email@example.com'
321
+ ADMIN_EMAIL = 'admin@example.com'
322
+ ```
323
+
324
+ These settings ensure that the email notifier is correctly configured to send log notifications to the specified `ADMIN_EMAIL` address.
325
+
326
+ ## Conclusion
327
+
328
+ Thank you for using `django_logging`. We hope this package enhances your Django application's logging capabilities. For more detailed documentation, customization options, and updates, please refer to the official documentation on [Read the Docs](https://django_logging.readthedocs.io/). If you have any questions or issues, feel free to open an issue on our [GitHub repository](https://github.com/ARYAN-NIKNEZHAD/django_logging).
329
+
330
+ Happy logging!
331
+
@@ -0,0 +1,294 @@
1
+ # Django Logging
2
+
3
+ The [`django_logging`](https://github.com/ARYAN-NIKNEZHAD/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.
4
+
5
+ ![License](https://img.shields.io/github/license/ARYAN-NIKNEZHAD/django_logging)
6
+ ![PyPI release](https://img.shields.io/pypi/v/django_logging)
7
+ ![Supported Python versions](https://img.shields.io/pypi/pyversions/django_logging)
8
+ ![Supported Django versions](https://img.shields.io/pypi/djversions/django_logging)
9
+ ![Documentation](https://img.shields.io/readthedocs/django_logging)
10
+ ![Last Commit](https://img.shields.io/github/last-commit/ARYAN-NIKNEZHAD/django_logging)
11
+ ![Languages](https://img.shields.io/github/languages/top/ARYAN-NIKNEZHAD/django_logging)
12
+ ![CI Workflow](https://github.com/ARYAN-NIKNEZHAD/django_logging/actions/workflows/ci.yml/badge.svg)
13
+ ![Open Issues](https://img.shields.io/github/issues/ARYAN-NIKNEZHAD/django_logging)
14
+ [![codecov](https://codecov.io/gh/ARYAN-NIKNEZHAD/django_logging/branch/main/graph/badge.svg)](https://codecov.io/gh/ARYAN-NIKNEZHAD/django_logging)
15
+
16
+
17
+ ## Project Detail
18
+
19
+ - Language: Python > 3.8
20
+ - Framework: Django > 4.2
21
+
22
+
23
+ ## Documentation
24
+
25
+ The documentation is organized into the following sections:
26
+
27
+ - [Quick Start](#quick-start)
28
+ - [Usage](#usage)
29
+ - [Settings](#settings)
30
+ - [Available Format Options](#available-format-options)
31
+ - [Required Email Settings](#required-email-settings)
32
+
33
+
34
+ ## Quick Start
35
+
36
+ Getting started with `django_logging` is simple. Follow these steps to get up and running quickly:
37
+
38
+ 1. **Install the Package**
39
+
40
+ first, Install `django_logging` via pip:
41
+
42
+ ```shell
43
+ $ pip install django_logging
44
+ ```
45
+
46
+ 2. **Add to Installed Apps**
47
+
48
+ Add `django_logging` to your `INSTALLED_APPS` in your Django settings file:
49
+
50
+ ```python
51
+ INSTALLED_APPS = [
52
+ ...
53
+ 'django_logging',
54
+ ...
55
+ ]
56
+ ```
57
+
58
+
59
+ 3. **Run Your Server**
60
+
61
+ Start your Django Development server to verify the installation:
62
+ ```shell
63
+ python manage.py runserver
64
+ ```
65
+
66
+ when the server starts, you'll see an initialization message like this in your *console*:
67
+ ```shell
68
+ INFO | 'datetime' | django_logging | Logging initialized with the following configurations:
69
+ Log File levels: ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'].
70
+ Log files are being written to: logs.
71
+ Console output level: DEBUG.
72
+ Colorize console: True.
73
+ Log date format: %Y-%m-%d %H:%M:%S.
74
+ Email notifier enabled: False.
75
+ ```
76
+ By default, django_logging will log each level to its own file:
77
+ - DEBUG : `logs/debug.log`
78
+ - INFO : `logs/info.log`
79
+ - WARNING : `logs/warning.log`
80
+ - ERROR : `logs/error.log`
81
+ - CRITICAL : `logs/critical.log`
82
+
83
+ In addition, logs will be displayed in ***colorized*** mode in the `console`, making it easier to distinguish between different log levels.
84
+
85
+ That's it! `django_logging` is ready to use. For further customization, refer to the [Settings](#settings) section
86
+
87
+
88
+ ## Usage
89
+ 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`.
90
+
91
+ 1. **Basic Logging Usage**
92
+
93
+ 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:
94
+ ```python
95
+ import logging
96
+
97
+ logger = logging.getLogger(__name__)
98
+
99
+ logger.debug("This is a debug message")
100
+ logger.info("This is an info message")
101
+ logger.warning("This is a warning message")
102
+ logger.error("This is an error message")
103
+ logger.critical("This is a critical message")
104
+ ```
105
+ 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.
106
+
107
+ 2. **Request Logging Middleware**
108
+
109
+ To log the detail of each request to the server and capture information such as the request path, user, IP address, and user agent, add `django_logging.middleware.RequestLogMiddleware` to your MIDDLEWARE setting:
110
+
111
+ ```python
112
+ MIDDLEWARE = [
113
+ ...
114
+ 'django_logging.middleware.RequestLogMiddleware',
115
+ ...
116
+ ]
117
+ ```
118
+
119
+ This middleware will log th request details at info level, here is an example with default format:
120
+ ```shell
121
+ INFO | 'datetime' | django_logging | Request Info: (request_path: /example-path, user: example_user,
122
+ IP: 192.168.1.1, user_agent: Mozilla/5.0)
123
+
124
+ ```
125
+
126
+ 3. **Context Manager**
127
+
128
+ You can use the `config_setup` context manager to temporarily apply `django_logging` configurations within a specific block of code.
129
+ Example usage:
130
+ ```python
131
+ from django_logging.utils.context_manager import config_setup
132
+ import logging
133
+
134
+ logger = logging.getLogger(__name__)
135
+
136
+ def foo():
137
+ logger.info("This log will use the configuration set in the context manager!")
138
+
139
+ with config_setup():
140
+ """ Your logging configuration changes here"""
141
+ foo()
142
+
143
+ # the logging configuration will restore to what it was before, in here outside of with block
144
+ ```
145
+ - 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:
146
+ ```
147
+ "You must set 'AUTO_INITIALIZATION_ENABLE' to False in DJANGO_LOGGING in your settings to use the context manager."
148
+ ```
149
+
150
+ 4. **Log and Notify Utility**
151
+
152
+ To send specific logs as email, use the `log_and_notify_admin` function. Ensure that the `ENABLE` option in `LOG_EMAIL_NOTIFIER` is set to `True` in your settings:
153
+ ```python
154
+ from django_logging.utils.log_email_notifier.log_and_notify import log_and_notify_admin
155
+ import logging
156
+
157
+ logger = logging.getLogger(__name__)
158
+
159
+ log_and_notify_admin(logger, logging.INFO, "This is a log message")
160
+ ```
161
+ You can also include additional request information (`ip_address` and `browser_type`) in the email by passing an `extra` dictionary:
162
+ ```python
163
+ from django_logging.utils.log_email_notifier.log_and_notify import log_and_notify_admin
164
+ import logging
165
+
166
+ logger = logging.getLogger(__name__)
167
+
168
+ def some_view(request):
169
+ log_and_notify_admin(
170
+ logger,
171
+ logging.INFO,
172
+ "This is a log message",
173
+ extra={"request": request}
174
+ )
175
+ ```
176
+
177
+ - 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`:
178
+ ```shell
179
+ "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."
180
+ ```
181
+
182
+ Additionally, ensure that all [Required Email Settings](#required-email-settings) are configured in your Django settings file.
183
+
184
+ 5. **Send Logs Command**
185
+
186
+ To send the entire log directory to a specified email address, use the `send_logs` management command:
187
+ ```shell
188
+ python manage.py send_logs example@domain.com
189
+ ```
190
+ This command will attach the log directory and send a zip file to the provided email address.
191
+
192
+ ## Settings
193
+
194
+ By default, `django_logging` uses a built-in configuration that requires no additional setup. However, you can customize the logging settings by adding the `DJANGO_LOGGING` dictionary configuration to your Django `settings` file.
195
+
196
+ Example configuration:
197
+ ```python
198
+ DJANGO_LOGGING = {
199
+ "AUTO_INITIALIZATION_ENABLE": True,
200
+ "INITIALIZATION_MESSAGE_ENABLE": True,
201
+ "LOG_FILE_LEVELS": ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
202
+ "LOG_DIR": "logs",
203
+ "LOG_FILE_FORMATS": {
204
+ "DEBUG": 1,
205
+ "INFO": 1,
206
+ "WARNING": 1,
207
+ "ERROR": 1,
208
+ "CRITICAL": 1,
209
+ },
210
+ "LOG_CONSOLE_LEVEL": "DEBUG",
211
+ "LOG_CONSOLE_FORMAT": 1,
212
+ "LOG_CONSOLE_COLORIZE": True,
213
+ "LOG_DATE_FORMAT": "%Y-%m-%d %H:%M:%S",
214
+ "LOG_EMAIL_NOTIFIER": {
215
+ "ENABLE": False,
216
+ "NOTIFY_ERROR": False,
217
+ "NOTIFY_CRITICAL": False,
218
+ "LOG_FORMAT": 1,
219
+ "USE_TEMPLATE": True
220
+ }
221
+ }
222
+ ```
223
+
224
+ Here's a breakdown of the available configuration options:
225
+ - `AUTO_INITIALIZATION_ENABLE`: Accepts `bool`. Enables automatic initialization of logging configurations. Defaults to `True`.
226
+ - `INITIALIZATION_MESSAGE_ENABLE`: Accepts bool. Enables logging of the initialization message. Defaults to `True`.
227
+ - `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']`.
228
+ - `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"`.
229
+ - `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.
230
+ - **Note**: See the [Available Format Options](#available-format-options) below for available formats.
231
+ - `LOG_CONSOLE_LEVEL`: Accepts `str` that is a valid log level. Specifies the log level for console output. Defaults to `'DEBUG'`.
232
+ - `LOG_CONSOLE_FORMAT`: Accepts the same options as `LOG_FILE_FORMATS`. Defines the format for console output. Defaults to `1`.
233
+ - `LOG_CONSOLE_COLORIZE`: Accepts `bool`. Determines whether to colorize console output. Defaults to `True`.
234
+ - `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'`.
235
+ - `LOG_EMAIL_NOTIFIER`: Is a dictionary where:
236
+ - `ENABLE`: Accepts `bool`. Determines whether the email notifier is enabled. Defaults to `False`.
237
+ - `NOTIFY_ERROR`: Accepts `bool`. Determines whether to notify on error logs. Defaults to `False`.
238
+ - `NOTIFY_CRITICAL`: Accepts `bool`. Determines whether to notify on critical logs. Defaults to `False`.
239
+ - `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`.
240
+ - `USE_TEMPLATE`: Accepts `bool`. Determines whether the email includes an HTML template. Defaults to `True`.
241
+
242
+ ## Available Format Options
243
+
244
+ The `django_logging` package provides predefined log format options that you can use in configuration. Below are the available format options:
245
+
246
+ ```python
247
+ FORMAT_OPTIONS = {
248
+ 1: "%(levelname)s | %(asctime)s | %(module)s | %(message)s",
249
+ 2: "%(levelname)s | %(asctime)s | %(message)s",
250
+ 3: "%(levelname)s | %(message)s",
251
+ 4: "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
252
+ 5: "%(levelname)s | %(message)s | [in %(pathname)s:%(lineno)d]",
253
+ 6: "%(asctime)s | %(levelname)s | %(message)s",
254
+ 7: "%(levelname)s | %(asctime)s | in %(module)s: %(message)s",
255
+ 8: "%(levelname)s | %(message)s | [%(filename)s:%(lineno)d]",
256
+ 9: "[%(asctime)s] | %(levelname)s | in %(module)s: %(message)s",
257
+ 10: "%(asctime)s | %(processName)s | %(name)s | %(levelname)s | %(message)s",
258
+ 11: "%(asctime)s | %(threadName)s | %(name)s | %(levelname)s | %(message)s",
259
+ 12: "%(levelname)s | [%(asctime)s] | (%(filename)s:%(lineno)d) | %(message)s",
260
+ 13: "%(levelname)s | [%(asctime)s] | {%(name)s} | (%(filename)s:%(lineno)d): %(message)s",
261
+ }
262
+ ```
263
+
264
+ You can reference these formats by their corresponding integer keys in your logging configuration settings.
265
+
266
+ ## Required Email Settings
267
+
268
+ To use the email notifier, the following email settings must be configured in your `settings.py`:
269
+ - `EMAIL_HOST`: The host to use for sending emails.
270
+ - `EMAIL_PORT`: The port to use for the email server.
271
+ - `EMAIL_HOST_USER`: The username to use for the email server.
272
+ - `EMAIL_HOST_PASSWORD`: The password to use for the email server.
273
+ - `EMAIL_USE_TLS`: Whether to use a TLS (secure) connection when talking to the email server.
274
+ - `DEFAULT_FROM_EMAIL`: The default email address to use for sending emails.
275
+ - `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.
276
+
277
+ Example Email Settings:
278
+ ```python
279
+ EMAIL_HOST = 'smtp.example.com'
280
+ EMAIL_PORT = 587
281
+ EMAIL_HOST_USER = 'your-email@example.com'
282
+ EMAIL_HOST_PASSWORD = 'your-password'
283
+ EMAIL_USE_TLS = True
284
+ DEFAULT_FROM_EMAIL = 'your-email@example.com'
285
+ ADMIN_EMAIL = 'admin@example.com'
286
+ ```
287
+
288
+ These settings ensure that the email notifier is correctly configured to send log notifications to the specified `ADMIN_EMAIL` address.
289
+
290
+ ## Conclusion
291
+
292
+ Thank you for using `django_logging`. We hope this package enhances your Django application's logging capabilities. For more detailed documentation, customization options, and updates, please refer to the official documentation on [Read the Docs](https://django_logging.readthedocs.io/). If you have any questions or issues, feel free to open an issue on our [GitHub repository](https://github.com/ARYAN-NIKNEZHAD/django_logging).
293
+
294
+ Happy logging!
File without changes