async def _message_loop(self): async for message in self.websocket: # Clear context vars for logging clear_contextvars() bind_contextvars(message=message) if message.type == aiohttp.WSMsgType.ERROR: await self.websocket_message_error(message) continue try: data = json.loads(message.data) except JSONDecodeError as exception: await self.websocket_message_not_parsable(message, exception) continue unbind_contextvars("message") # bind_contextvars(data=data) if "msg" not in data: await self.websocket_message_missing_data_msg(data) continue num_fired = self.websocket_event_system.fire_event( event=data["msg"], data=data) if num_fired == 0: await self.missing_message_handler(data)
def bind_client_name_to_logger(name: str): # type:ignore if name: bind_contextvars(client=name) try: yield finally: unbind_contextvars("client")
def _bind_context(**kwargs): """Context manager to bind logging contextvars.""" # Filter None values before binding vars filtered_kwargs = { key: value for (key, value) in kwargs.items() if value is not None } bind_contextvars(**filtered_kwargs) yield unbind_contextvars(*filtered_kwargs.keys())
def bind_remote_address_to_logger(sock: socket.socket): # type:ignore try: bind_contextvars(remote=sock.getpeername()) except socket.error: pass try: yield finally: unbind_contextvars("remote")
def on_response(request: Request, response: HTTPResponse) -> None: """Middleware function that runs prior to returning a response via Sanic.""" logger.debug( 'returning HTTP response', request=f'{request.method} {request.url}', status=response.status, bytes=len(response.body), ) # Unbind the request ID from the logger. contextvars.unbind_contextvars('request_id', )
def on_response(request: Request, response: HTTPResponse) -> None: """Middleware function that runs prior to returning a response via Sanic.""" # Default bytes. If this is a StreamingHTTPResponse, this value is # used, since there is no response.body for those responses. # (https://github.com/vapor-ware/synse-server/issues/396) byte_count = -1 if hasattr(response, 'body') and response.body is not None: byte_count = len(response.body) logger.debug( 'returning HTTP response', request=f'{request.method} {request.url}', status=response.status, bytes=byte_count, ) # Unbind the request ID from the logger. contextvars.unbind_contextvars( 'request_id', )
def process(meta_data: MetaWrapper, data_bytes: bytes) -> Response: """ Binds submission data to logger and begins deliver process """ try: bind_contextvars(tx_id=meta_data.tx_id, survey_id=meta_data.survey_id, output_type=meta_data.output_type, thread=threading.currentThread().getName()) logger.info("Processing request") deliver(meta_data, data_bytes) """ WE USE THE BELOW LOG MESSAGE "logger.info("Process completed successfully")" TO CREATE "LOG-BASED" CUSTOM METRICS. DO NOT CHANGE THIS STATEMENT. """ logger.info("Process completed successfully") return jsonify(success=True) except Exception as e: return server_error(e) finally: unbind_contextvars('tx_id', 'survey_id', 'output_type', 'thread')
async def coro(): # Since unbinding means "setting to Ellipsis", we have to make # some effort to ensure that the ContextVar never existed. unbind_contextvars("a" + secrets.token_hex()) return merge_contextvars(None, None, {"b": 2})
async def coro(): bind_contextvars(a=1) unbind_contextvars("a") return merge_contextvars(None, None, {"b": 2})
def __exit__(self, exc_type, exc_value, exc_traceback): [contextvars.unbind_contextvars(key) for key in self._context] contextvars.bind_contextvars(**self._existing_vars)