Skip to content

Commit fb84a83

Browse files
committed
Add how to customize the formatter
1 parent ff80902 commit fb84a83

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

README.rst

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ JSON libraries
3737
--------------
3838

3939
You can use **ujson** or **simplejson** instead of built-in **json** library.
40-
They are faster and can serialize `Decimal` values.
40+
They are faster and can serialize ``Decimal`` values.
4141

4242
.. code-block:: python
4343
@@ -78,6 +78,36 @@ Let's try to log something.
7878
7979
logger.info('Sign up', extra={'referral_code': '52d6ce'})
8080
81+
Custom formatter
82+
----------------
83+
84+
You will likely need a custom log format. For instance, you want to log
85+
a user ID, an IP address and ``time`` as ``django.utils.timezone.now()``.
86+
To do so you should override ``JSONFormatter.json_record()``.
87+
88+
.. code-block:: python
89+
90+
class CustomisedJSONFormatter(json_log_formatter.JSONFormatter):
91+
def json_record(self, message, extra, record):
92+
extra['message'] = message
93+
extra['user_id'] = current_user_id()
94+
extra['ip'] = current_ip()
95+
if 'time' not in extra:
96+
extra['time'] = django.utils.timezone.now()
97+
return extra
98+
99+
Let's say you want ``datetime`` to be serialized as timestamp.
100+
Then you should use **ujson** (which does it by default) and disable
101+
ISO8601 date mutation.
102+
103+
.. code-block:: python
104+
105+
class CustomisedJSONFormatter(json_log_formatter.JSONFormatter):
106+
json_lib = ujson
107+
108+
def mutate_json_record(self, json_record):
109+
pass
110+
81111
Tests
82112
-----
83113

0 commit comments

Comments
 (0)