# JSONFormatter
Part of [[distillery_aws]]
The `JSONFormatter` class is a custom logging formatter that converts log records into JSON format. It inherits from the `logging.Formatter` class and overrides the `format` method to customize the log message format.
```python
class JSONFormatter(logging.Formatter):
def format(self, record):
log_record = record.__dict__.copy()
# Check if 'msg' is already in JSON format
try:
log_dict = json.loads(log_record['msg'])
except Exception as e:
log_dict = copy.deepcopy(log_record['msg'])
log_dict['level'] = record.levelname
# return the JSON string
return json.dumps(log_dict)
```
The `format` method takes a log record as input and performs the following steps:
1. Creates a copy of the log record's `__dict__` attribute to avoid modifying the original record.
2. Attempts to parse the `msg` attribute of the log record as JSON using `json.loads()`.
3. If parsing fails, creates a deep copy of the `msg` attribute using `copy.deepcopy()` to handle non-JSON messages.
4. Adds the log level (`levelname`) to the `log_dict` dictionary.
5. Serializes the `log_dict` dictionary into a JSON string using `json.dumps()` and returns it as the formatted log message.