async def error(): Logger.error("This is a test error log entry") try: raise NotImplementedError() except Exception as ex: Logger.error("This is a test error log entry with extra info", ex) return {"logger": Logger.logger_type()}
def __get_token(request: Request): if "Authorization" not in request.headers: return None header = request.headers["Authorization"] try: parts = header.split(" ") if len(parts) < 2: Logger.warn("Invalid bearer token (less than 2 parts)") return None token = parts[1] # Logger.info(token) token = auth.verify_id_token(token, check_revoked=True) uid = token["uid"] request.state.uid = uid context.data["user_id"] = uid return token except auth.ExpiredIdTokenError: Logger.warn("Expired token encountered") except auth.InvalidIdTokenError: Logger.warn("Invalid token encountered") except BaseException as ex: Logger.error("Exception occurred while decoding token", exc_info=ex) return None
def run_check(name: str, target: Callable): try: Logger.info(f"Starting test '{name}'") target() Logger.info(f"Test '{name}' completed successfully") return True except BaseException as ex: Logger.error(f"Test '{name}' failed", exc_info=ex) return False
def __check_api_key(request: Request) -> dict: key = request.query_params.get("key", None) try: config = get_settings() return key == config.api_key except Exception as ex: Logger.error("Error occurred while checking api key for request", exc_info=ex) return None
def create_topic(self, topic_name: str): topic_path = self.get_topic_path(topic_name) try: try: self.publisher.get_topic(topic=topic_path) Logger.info("Topic exists", extra={"topic_name": topic_name}) except NotFound: self.publisher.create_topic(name=topic_path) Logger.info("Topic created", extra={"topic_name": topic_name}) except BaseException as ex: Logger.error("Failed to create topic", extra={"topic_name": topic_name}, exc_info=ex) raise ex
def execute(self, command: TCommand) -> TResult: name = type(self).__name__ extra = {"command": command.json()} Logger.info(f"{name} executing", extra=extra) try: result = self.on_execute(command) except Exception as ex: Logger.error(f"Error executing {name}", exc_info=ex, extra=extra) raise ex Logger.info(f"{name} completed") return result
def create_push_subscription( self, subscription_name: str, topic_name: str, endpoint: str, config: SubscriptionConfig = None) -> Subscription: subscriber: SubscriberWrapper = SubscriberClient() subcription_path = subscriber.subscription_path( self.project_id, subscription_name) topic_path = self.get_topic_path(topic_name) if not config: config = SubscriptionConfig() logging_extra = { "subscription_name": subscription_name, "topic_name": topic_name, "config": config.dict(), } with subscriber: try: try: subscription = subscriber.get_subscription( request={"subscription": subcription_path}) Logger.info("Push subscription exists", logging_extra) return subscription except NotFound: request = Subscription( name=subcription_path, topic=topic_path, push_config=PushConfig(push_endpoint=endpoint), ack_deadline_seconds=60, expiration_policy=ExpirationPolicy(ttl=Duration( seconds=config.expiration_days * 86400) if config.expiration_days else None), retry_policy=RetryPolicy(), message_retention_duration=Duration( seconds=config.retention_days * 86400)) subscription = subscriber.create_subscription( request=request) Logger.info("Push subscription created", logging_extra) return subscription except BaseException as ex: Logger.error("Failed to create push subscription", exc_info=ex, extra=logging_extra) raise ex
def update(transaction): owner = self.league_owned_player_repo.get(command.league_id, command.player.id, transaction) if not owner: # ignore and ack message, no one owns this player return UpdateLeaguePlayerDetailsResult(command=command) roster = self.league_roster_repo.get(command.league_id, owner.owner_id, transaction) positions: List[LeaguePosition] = [] for position_id in roster.positions: position = roster.positions[position_id] if position.player and position.player.id == command.player.id: positions.append(position) if len(positions) == 0: # something is messed up, the owned players list says someone owns this guy, # but we couldn't find him in that roster Logger.error( "League owned player list / league roster mismatch", extra={ "league_id": command.league_id, "player_id": command.player.id, "owner_id": owner.id, }) # but, I don't want this message to stick around forever. return UpdateLeaguePlayerDetailsResult(command=command) if len(positions) > 1: # how is this guy in two spots at once? Logger.error( "League owned player list / duplicate on league roster", extra={ "league_id": command.league_id, "player_id": command.player.id, "owner_id": owner.id, }) # should probably make this a really visible error - the players may let me know too though. # I'll still update this player since I'll use a loop for position in positions: position.player = command.player self.league_roster_repo.set(command.league_id, roster, transaction) return UpdateLeaguePlayerDetailsResult(command=command)
def get(self, path: str) -> dict: url = f"{self.settings.cfl_api_endpoint}/{path}" url_no_key = url if "?" in url: url += f"&key={self.settings.cfl_api_key}" else: url += f"?key={self.settings.cfl_api_key}" Logger.info(f"[CFL API] Fetching {url_no_key}") response = requests.get(url) if response.ok: return response.json() else: Logger.error( f"[CFL API] Error fetching data from {url_no_key}: {response.text}" ) raise CflApiException(response.text)
def on_execute(self, command: RegisterEmailCommand) -> RegisterEmailResult: existing = self.user_repository.get_by_email(command.email) if existing: return RegisterEmailResult(command=command, error="A user with that email already exists") try: result = auth.create_user(display_name=command.display_name, email=command.email) # type: UserRecord except auth.EmailAlreadyExistsError: return RegisterEmailResult(command=command, error="A user with that email already exists") except Exception as ex: Logger.error("Create user call failed", exc_info=ex) return RegisterEmailResult(command=command, error="Unable to create user account") if self.is_dev: # In live, this is handled by a background cloud function triggered after the registration user = User(id=result.uid, display_name=command.display_name, email=command.email, login_type=LoginType.EMAIL, confirmed=True) self.user_repository.create(user) return RegisterEmailResult(command=command)
def smoke_test(state_repo: StateRepository = Depends( create_state_repository)) -> Tuple[List[str], List[str]]: checks = { "firebase:state": state_repo.get, } Logger.info("Smoke test started") passes: List[str] = [] failures: List[str] = [] for name in checks: check = checks[name] passed = run_check(name, check) if passed: passes.append(name) else: failures.append(name) if failures: Logger.error("Smoke test completed with errors") else: Logger.info("Smoke test completed successfully") return passes, failures