Ejemplo n.º 1
0
def setup_logging(*,
                  level: Union[str, int],
                  slow_duration: Optional[float] = None):
    # service log level
    logging.basicConfig(level=level)

    # root
    logging.root.setLevel(level)
    config_all_loggers()

    # aiohttp access log-levels
    access_logger.setLevel(level)

    # keep mostly quiet noisy loggers
    quiet_level: int = max(
        min(logging.root.level + LOG_LEVEL_STEP, logging.CRITICAL),
        logging.WARNING)
    logging.getLogger("engineio").setLevel(quiet_level)
    logging.getLogger("openapi_spec_validator").setLevel(quiet_level)
    logging.getLogger("sqlalchemy").setLevel(quiet_level)
    logging.getLogger("sqlalchemy.engine").setLevel(quiet_level)

    if slow_duration:
        # NOTE: Every task blocking > AIODEBUG_SLOW_DURATION_SECS secs is considered slow and logged as warning
        log_slow_callbacks.enable(abs(slow_duration))
Ejemplo n.º 2
0
def init_app(settings: Optional[AppSettings] = None) -> FastAPI:
    if settings is None:
        settings = AppSettings.create_from_envs()
    assert settings  # nosec

    logging.basicConfig(level=settings.LOG_LEVEL.value)
    logging.root.setLevel(settings.LOG_LEVEL.value)
    logger.debug("App settings:\n%s", settings.json(indent=2))

    # creates app instance
    app = FastAPI(
        debug=settings.debug,
        title="osparc.io web API",
        description="osparc-simcore public web API specifications",
        version=API_VERSION,
        openapi_url=f"/api/{API_VTAG}/openapi.json",
        docs_url="/dev/doc",
        redoc_url=None,  # default disabled, see below
    )
    override_openapi_method(app)

    app.state.settings = settings

    # setup modules
    if settings.SC_BOOT_MODE == BootModeEnum.DEBUG:
        remote_debug.setup(app)

    if settings.API_SERVER_WEBSERVER:
        webserver.setup(app, settings.API_SERVER_WEBSERVER)

    if settings.API_SERVER_CATALOG:
        catalog.setup(app, settings.API_SERVER_CATALOG)

    if settings.API_SERVER_STORAGE:
        storage.setup(app, settings.API_SERVER_STORAGE)

    if settings.API_SERVER_DIRECTOR_V2:
        director_v2.setup(app, settings.API_SERVER_DIRECTOR_V2)

    # setup app
    app.add_event_handler("startup", create_start_app_handler(app))
    app.add_event_handler("shutdown", create_stop_app_handler(app))

    app.add_exception_handler(HTTPException, http_error_handler)
    app.add_exception_handler(RequestValidationError, http422_error_handler)
    app.add_exception_handler(HTTPStatusError, httpx_client_error_handler)

    # SEE https://docs.python.org/3/library/exceptions.html#exception-hierarchy
    app.add_exception_handler(
        NotImplementedError,
        make_http_error_handler_for_exception(
            status.HTTP_501_NOT_IMPLEMENTED, NotImplementedError
        ),
    )
    app.add_exception_handler(
        Exception,
        make_http_error_handler_for_exception(
            status.HTTP_500_INTERNAL_SERVER_ERROR,
            Exception,
            override_detail_message="Internal error"
            if settings.SC_BOOT_MODE == BootModeEnum.DEBUG
            else None,
        ),
    )

    # routing

    # healthcheck at / and at /vX/
    app.include_router(health_router)

    # docs
    redoc_html = create_redoc_handler(app)
    app.add_route("/doc", redoc_html, name="redoc_html", include_in_schema=False)

    # api under /v*
    api_router = create_router(settings)
    app.include_router(api_router, prefix=f"/{API_VTAG}")

    use_route_names_as_operation_ids(app)
    config_all_loggers()
    return app
Ejemplo n.º 3
0
    set_logging_handler,
    config_all_loggers,
)


@after_setup_logger.connect
def setup_loggers(logger, *_args, **_kwargs):
    """ Customizes global loggers """
    set_logging_handler(logger)


class TaskColoredFormatter(TaskFormatter, CustomFormatter):
    pass


@after_setup_task_logger.connect
def setup_task_logger(logger, *_args, **_kwargs):
    """ Customizes task loggers """

    set_logging_handler(
        logger,
        formatter_base=TaskColoredFormatter,
        formatting=
        "%(levelname)s: [%(asctime)s/%(processName)s][%(task_name)s(%(task_id)s)] [%(filename)s:%(lineno)d] %(message)s",
    )


config_all_loggers()
log = get_task_logger(__name__)
log.info("Setting up loggers")