Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Code Reviews

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

60%
+1 −0
Code Reviews JSON log formatter

PEP 8 Four-space indentation is the community standard. There are many strategies for wrapping long lines; I have found that it's often best to just use temporary variables to avoid wrapping lines...

posted 12mo ago by Karl Knechtel‭

Answer
#1: Initial revision by user avatar Karl Knechtel‭ · 2024-01-16T02:54:43Z (12 months ago)
## PEP 8

Four-space indentation is the community standard. There are many strategies for wrapping long lines; I have found that it's often best to just use temporary variables to avoid wrapping lines.

## Avoid pointless classes

The `UncaughtExceptionHook` class is a textbook example of the design Jack Diederich warns against in the provocatively-titled talk [Stop Writing Classes](https://www.youtube.com/watch?v=o9pEzgHorH0). It really only exists to "bind" the `logger` to later calls of `exception_hook`; it doesn't conceptually represent any more than the callback function itself does, it doesn't need to modify internal state, and it only provides a single interface method. This makes it a prime candidate for refactoring to use a simple function with `functools.partial`. As for registering the resulting exception hook, that can be done with a simple wrapper function.

```
import functools, sys

def log_uncaught_exception(logger, exc_type, exc_value, exc_traceback):
    exc_info = (ex_type, ex_value, ex_traceback)
    logger.critical(f"Unhandled exception.", exc_info=exc_info)
    sys.exit(1)

def set_logging_exception_hook(logger):
    sys.excepthook = functools.partial(log_uncaught_exception, logger)
```
Now there is a simple imperative interface for something that looks like an imperative task, rather than an object-oriented interface for something that doesn't look at all like a modeling task.

## Avoid boilerplate

`JsonLogFormatter.__init__` currently doesn't do anything different from the default. There is no benefit to writing anything here; wait until there is something to specify.

## Simpler dict construction

Agreed that `update` is overkill for adding a single key. Aside from that, dict unpacking can be used to simplify the syntax.

Putting the previous two hints together:

```
class JsonLogFormatter(logging.Formatter):
    def format(self, record):
        data = {
            "time": self.formatTime(record),
            "level": record.levelname,
            "message": record.message
        }
        if record.exc_info is not None:
            data["exception"] = self.formatException(record.exc_info)
        return json.dumps({**data, **record.args}, indent=None)
```