File size: 2,154 Bytes
1a3fc6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import logging
import colorlog
import sys
import time


def initialize_logger(name, level=logging.WARNING):
    logger = logging.getLogger(name)
    logger.propagate = False
    handler = colorlog.StreamHandler(stream=sys.stdout)
    formatter = colorlog.ColoredFormatter(
        "%(log_color)s[%(asctime)s][%(levelname)s][%(module)s]:%(reset)s %(message)s",
        reset=True,
        log_colors={
            "DEBUG": "cyan",
            "INFO": "green",
            "WARNING": "yellow",
            "ERROR": "red",
            "CRITICAL": "red,bg_white",
        },
    )
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(level)
    return logger


def catch_and_log_exceptions_for_sio_event_handlers(sio, logger):
    # wrapper should have the same signature as the original function
    def decorator(func):
        async def catch_exception_wrapper(*args, **kwargs):
            try:
                return await func(*args, **kwargs)
            except Exception as e:
                message = f"[app_pubsub] Caught exception in '{func.__name__}' event handler:\n\n{e}"
                logger.exception(message, stack_info=True)

                try:
                    exception_data = {
                        "message": message,
                        "timeEpochMs": int(time.time() * 1000),
                    }

                    # For now let's emit this to all clients. We ultimatley may want to emit it just to the room it's happening in.
                    await sio.emit("server_exception", exception_data)
                except Exception as inner_e:
                    logger.exception(
                        f"[app_pubsub] Caught exception while trying to emit server_exception event:\n{inner_e}"
                    )

                # Re-raise the exception so it's handled normally by the server
                raise e

        # Set the name of the wrapper to the name of the original function so that the socketio server can associate it with the right event
        catch_exception_wrapper.__name__ = func.__name__
        return catch_exception_wrapper

    return decorator