Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SIANXKE-178: 'details' column + test fix (message_only handler) #31

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,48 @@ Options
1. DJANGO_DB_LOGGER_ADMIN_LIST_PER_PAGE: integer. list per page in admin view. default ``10``
2. DJANGO_DB_LOGGER_ENABLE_FORMATTER: boolean. Using ``formatter`` options to format message. ``True`` or ``False``, default ``False``


Define your own behaviour to log additional details:
----------------------------------------------------
Extend the ``DatabaseLogHandler`` to add your own configurations and functionality to the ``add_details`` method:

.. code-block:: python

# my_log_handlers.py
from django_db_logger.db_log_handler import DatabaseLogHandler

class MyDatabaseLogHandler(DatabaseLogHandler):
def add_details(self, record, log_fields):
"""
Extract relevant details from the record's request:
* request path
* used HTTP method
* used GET params (within URL)
"""
request = getattr(record, 'request', None)
if request:
log_fields['details'] = {
'path': getattr(request, 'path', None),
'method': getattr(request, 'method', None),
'params': getattr(request, 'GET', None),
}


And make sure to use your own class in the logging configuration:
.. code-block:: python

# settings.py
LOGGING["handlers"]["db_log"] = {
"class": "my_project.my_log_handlers.MyDatabaseLogHandler",
"level": "DEBUG",
}


Build your own database logger :hammer:
---------------------------------------
1. Create a new app and add it to ``INSTALLED_APPS``
2. Copy files ``django-db-logger/models.py``, ``django-db-logger/admin.py``, ``django-db-logger/db_log_handler.py`` to the app folder
3. Replace ``DJANGO_DB_LOGGER_ADMIN_LIST_PER_PAGE`` in ``admin.py`` with an integer
4. Replace ``DJANGO_DB_LOGGER_ENABLE_FORMATTER`` in `db_log_handler.py` with ``True`` or ``False``. Remove ``MSG_STYLE_SIMPLE``, it was not used.
5. Replace logger class ``django_db_logger.db_log_handler.DatabaseLogHandler`` in your Settings with the new logger class
6. Customize the looger to meet your needs. :beer:
6. Customize the logger to meet your needs. :beer:
9 changes: 6 additions & 3 deletions dev_env/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,19 @@
'simple': {
'format': '%(levelname)s %(asctime)s %(message)s'
},
'message_only': {
'format': '%(message)s'
}
},
'handlers': {
'db_handler': {
'level': 'DEBUG',
'class': 'django_db_logger.db_log_handler.DatabaseLogHandler',
'formatter': 'verbose'
'formatter': 'message_only'
}
},
'loggers': {
'db': {
'db_logger': {
'handlers': ['db_handler'],
'level': 'DEBUG'
}
Expand Down Expand Up @@ -116,4 +119,4 @@

USE_L10N = True

USE_TZ = True
USE_TZ = True
14 changes: 11 additions & 3 deletions django_db_logger/db_log_handler.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import logging

from django_db_logger.config import DJANGO_DB_LOGGER_ENABLE_FORMATTER, MSG_STYLE_SIMPLE

from django_db_logger.config import DJANGO_DB_LOGGER_ENABLE_FORMATTER

db_default_formatter = logging.Formatter()


class DatabaseLogHandler(logging.Handler):
def emit(self, record):
from .models import StatusLog

trace = None

if record.exc_info:
Expand All @@ -27,6 +26,9 @@ def emit(self, record):
'trace': trace
}

# extract relevant log details from the record
self.add_details(record, kwargs)

StatusLog.objects.create(**kwargs)

def format(self, record):
Expand All @@ -46,3 +48,9 @@ def format(self, record):
return fmt.formatMessage(record)
else:
return fmt.format(record)

def add_details(self, record, log_fields):
"""
Add the record's relevant details to the log_fields
"""
pass
18 changes: 18 additions & 0 deletions django_db_logger/migrations/0003_statuslog_details.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 3.2.12 on 2022-02-16 14:46

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('django_db_logger', '0002_auto_20190109_0052'),
]

operations = [
migrations.AddField(
model_name='statuslog',
name='details',
field=models.JSONField(help_text='Additional info about the log (e.g. GET request path and query params).', null=True, verbose_name='details'),
),
]
6 changes: 6 additions & 0 deletions django_db_logger/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ class StatusLog(models.Model):
msg = models.TextField()
trace = models.TextField(blank=True, null=True)
create_datetime = models.DateTimeField(auto_now_add=True, verbose_name='Created at')
details = models.JSONField(
_("details"),
help_text=_("Additional info about the log (e.g. GET request path and query params)."),
blank=False,
null=True,
)

def __str__(self):
return self.msg
Expand Down