0
# Standard JSON Formatting
1
2
JSON formatting using Python's built-in json module with custom encoder support for handling extended Python types. This is the default and most compatible formatter.
3
4
## Core Imports
5
6
```python
7
from pythonjsonlogger.json import JsonFormatter, JsonEncoder
8
```
9
10
For type checking:
11
12
```python
13
from typing import Union, Callable, Optional, Any
14
import json
15
```
16
17
## Capabilities
18
19
### JsonFormatter Class
20
21
Main JSON formatter using Python's standard library json module for serialization.
22
23
```python { .api }
24
class JsonFormatter(BaseJsonFormatter):
25
def __init__(
26
self,
27
*args,
28
json_default: OptionalCallableOrStr = None,
29
json_encoder: OptionalCallableOrStr = None,
30
json_serializer: Union[Callable, str] = json.dumps,
31
json_indent: Optional[Union[int, str]] = None,
32
json_ensure_ascii: bool = True,
33
**kwargs,
34
) -> None:
35
"""
36
Standard JSON formatter initialization.
37
38
Parameters:
39
- args: see BaseJsonFormatter
40
- json_default: function for encoding non-standard objects
41
- json_encoder: custom JSON encoder class
42
- json_serializer: json.dumps-compatible callable for serialization
43
- json_indent: indent parameter for json_serializer
44
- json_ensure_ascii: ensure_ascii parameter for json_serializer
45
- kwargs: see BaseJsonFormatter
46
"""
47
48
def jsonify_log_record(self, log_record: LogRecord) -> str:
49
"""
50
Convert log record to JSON string.
51
52
Parameters:
53
- log_record: dictionary containing log data
54
55
Returns:
56
JSON string representation of the log record
57
"""
58
```
59
60
### JsonEncoder Class
61
62
Custom JSON encoder that extends json.JSONEncoder to handle additional Python types.
63
64
```python { .api }
65
class JsonEncoder(json.JSONEncoder):
66
def default(self, o: Any) -> Any:
67
"""
68
Override default serialization for non-standard types.
69
70
Handles datetime objects, exceptions, tracebacks, enums, bytes,
71
dataclasses, type objects, and unknown types.
72
73
Parameters:
74
- o: object to serialize
75
76
Returns:
77
Serializable representation of the object
78
"""
79
80
def format_datetime_obj(self, o: datetime.time | datetime.date | datetime.datetime) -> str:
81
"""
82
Format datetime objects for JSON serialization.
83
84
Parameters:
85
- o: datetime object to format
86
87
Returns:
88
ISO format string representation
89
"""
90
```
91
92
### Deprecated Module Access
93
94
The json module supports deprecated access to constants from other modules for backward compatibility.
95
96
```python { .api }
97
# Deprecated - use pythonjsonlogger.core.RESERVED_ATTRS instead
98
from pythonjsonlogger.json import RESERVED_ATTRS # Issues deprecation warning
99
```
100
101
## Usage Examples
102
103
### Basic JSON Formatter Setup
104
105
```python
106
import logging
107
from pythonjsonlogger.json import JsonFormatter
108
109
# Create logger with JSON formatter
110
logger = logging.getLogger('my_app')
111
handler = logging.StreamHandler()
112
formatter = JsonFormatter('%(levelname)s %(name)s %(message)s')
113
handler.setFormatter(formatter)
114
logger.addHandler(handler)
115
116
# Log with extra fields
117
logger.info("User logged in", extra={"user_id": 123, "ip": "192.168.1.1"})
118
```
119
120
### Custom JSON Encoder
121
122
```python
123
import json
124
from pythonjsonlogger.json import JsonFormatter, JsonEncoder
125
126
class CustomEncoder(JsonEncoder):
127
def format_datetime_obj(self, o):
128
# Custom datetime formatting
129
return o.strftime('%Y-%m-%d %H:%M:%S UTC')
130
131
# Use custom encoder
132
formatter = JsonFormatter(
133
'%(levelname)s %(message)s',
134
json_encoder=CustomEncoder
135
)
136
```
137
138
### Custom Serializer Options
139
140
```python
141
from pythonjsonlogger.json import JsonFormatter
142
import json
143
144
# Pretty-printed JSON with custom options
145
formatter = JsonFormatter(
146
'%(levelname)s %(name)s %(message)s',
147
json_indent=2,
148
json_ensure_ascii=False,
149
json_serializer=json.dumps
150
)
151
```
152
153
### Custom Default Function
154
155
```python
156
from pythonjsonlogger.json import JsonFormatter
157
import decimal
158
159
def custom_default(obj):
160
if isinstance(obj, decimal.Decimal):
161
return float(obj)
162
raise TypeError(f"Object {obj} is not JSON serializable")
163
164
formatter = JsonFormatter(
165
'%(levelname)s %(message)s',
166
json_default=custom_default
167
)
168
```
169
170
## Type Handling
171
172
The JsonEncoder automatically handles these Python types:
173
174
- **datetime.datetime, datetime.date, datetime.time**: Converted to ISO format strings
175
- **Exception objects**: Converted to "ExceptionClass: message" format
176
- **Traceback objects**: Converted to formatted traceback strings
177
- **Enum objects**: Converted to their values
178
- **bytes/bytearray**: Converted to base64 strings
179
- **dataclass instances**: Converted to dictionaries
180
- **type objects**: Converted to class names
181
- **Unknown types**: Fallback to str() or repr(), or "__could_not_encode__"