codekingpro/portable-devtools
114k
1# --------------------------------------------------------------------------2#3# Copyright (c) Microsoft Corporation. All rights reserved.4#5# The MIT License (MIT)6#7# Permission is hereby granted, free of charge, to any person obtaining a copy8# of this software and associated documentation files (the ""Software""), to9# deal in the Software without restriction, including without limitation the10# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or11# sell copies of the Software, and to permit persons to whom the Software is12# furnished to do so, subject to the following conditions:13#14# The above copyright notice and this permission notice shall be included in15# all copies or substantial portions of the Software.16#17# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING22# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS23# IN THE SOFTWARE.24#25# --------------------------------------------------------------------------26 27import logging28import re29import types30 31from typing import Any, Optional, TYPE_CHECKING # pylint: disable=unused-import32 33if TYPE_CHECKING:34 from .universal_http import ClientRequest, ClientResponse # pylint: disable=unused-import35 36_LOGGER = logging.getLogger(__name__)37 38 39def log_request(_, request, *_args, **_kwargs):40 # type: (Any, ClientRequest, str, str) -> None41 """Log a client request.42 43 :param _: Unused in current version (will be None)44 :param requests.Request request: The request object.45 """46 if not _LOGGER.isEnabledFor(logging.DEBUG):47 return48 49 try:50 _LOGGER.debug("Request URL: %r", request.url)51 _LOGGER.debug("Request method: %r", request.method)52 _LOGGER.debug("Request headers:")53 for header, value in request.headers.items():54 if header.lower() == 'authorization':55 value = '*****'56 _LOGGER.debug(" %r: %r", header, value)57 _LOGGER.debug("Request body:")58 59 # We don't want to log the binary data of a file upload.60 if isinstance(request.body, types.GeneratorType):61 _LOGGER.debug("File upload")62 else:63 _LOGGER.debug(str(request.body))64 except Exception as err: # pylint: disable=broad-except65 _LOGGER.debug("Failed to log request: %r", err)66 67 68def log_response(_, _request, response, *_args, **kwargs):69 # type: (Any, ClientRequest, ClientResponse, str, Any) -> Optional[ClientResponse]70 """Log a server response.71 72 :param _: Unused in current version (will be None)73 :param requests.Request request: The request object.74 :param requests.Response response: The response object.75 """76 if not _LOGGER.isEnabledFor(logging.DEBUG):77 return None78 79 try:80 _LOGGER.debug("Response status: %r", response.status_code)81 _LOGGER.debug("Response headers:")82 for res_header, value in response.headers.items():83 _LOGGER.debug(" %r: %r", res_header, value)84 85 # We don't want to log binary data if the response is a file.86 _LOGGER.debug("Response content:")87 pattern = re.compile(r'attachment; ?filename=["\w.]+', re.IGNORECASE)88 header = response.headers.get('content-disposition')89 90 if header and pattern.match(header):91 filename = header.partition('=')[2]92 _LOGGER.debug("File attachments: %s", filename)93 elif response.headers.get("content-type", "").endswith("octet-stream"):94 _LOGGER.debug("Body contains binary data.")95 elif response.headers.get("content-type", "").startswith("image"):96 _LOGGER.debug("Body contains image data.")97 else:98 if kwargs.get('stream', False):99 _LOGGER.debug("Body is streamable")100 else:101 _LOGGER.debug(response.text())102 return response103 except Exception as err: # pylint: disable=broad-except104 _LOGGER.debug("Failed to log response: %s", repr(err))105 return response106 