লগিং

লগিং ও মনিটরিং একসাথে কাজ করে যাতে আপনি অ্যাপ্লিকেশন পারফর্ম্যান্স বুঝতে ও অপ্টিমাইজ করতে পারেন, সেইসাথে ভুলত্রুটি ও সিস্টেম-সম্পর্কিত সমস্যা ডায়াগনসিস করতে পারেন। সব API কলের জন্য সারসংক্ষেপ লগ এবং যেসব API কল কাজ করেনি সেগুলির জন্য বিস্তারিত লগ চালু করা উচিত, যাতে টেকনিক্যাল সহায়তা প্রয়োজন হলে আপনি API কল লগ প্রদান করতে পারেন।

ক্লায়েন্ট লাইব্রেরি লগিং

Google Ads API ক্লায়েন্ট লাইব্রেরিতে বিল্ট-ইন লগিংয়ের সুবিধা আছে। প্ল্যাটফর্ম-নির্দিষ্ট লগিংয়ের বিবরণের জন্য, আপনার পছন্দের ক্লায়েন্ট লাইব্রেরির মধ্যে লগিং ডকুমেন্টেশন দেখুন।

ভাষা গাইড
Java Java-এর জন্য লগিং ডকুমেন্ট
.NET .NET-এর জন্য লগিং ডকুমেন্ট
PHP PHP-এর জন্য লগিং ডকুমেন্ট
Python Python-এর জন্য লগিং ডকুমেন্ট
Ruby Ruby-র জন্য লগিং ডকুমেন্ট
Perl Perl-এর জন্য লগিং ডকুমেন্ট

লগ ফর্ম্যাট

Google Ads API ক্লায়েন্ট লাইব্রেরি প্রতিটি API কলের জন্য একটি বিস্তারিত লগ এবং একটি সারসংক্ষেপ লগ তৈরি করে। বিস্তারিত লগে API কলের সব বিবরণ থাকে, অন্যদিকে সারসংক্ষেপ লগে API কলের ন্যূনতম বিবরণ থাকে। প্রতিটি ধরনের লগ কেমন হয় তার একটি করে উদাহরণ দেখানো হয়েছে, যেখানে লগগুলি পাঠযোগ্য করে তোলার জন্য ছোট করে ফর্ম্যাট করা হয়েছে।

লগের সারসংক্ষেপ

GoogleAds.SummaryRequestLogs Warning: 1 : [2023-09-15 19:58:39Z] -
Request made: Host: ,
Method: /google.ads.googleads.v26.services.GoogleAdsService/SearchStream,
ClientCustomerID: 5951878031, RequestID: hELhBPNlEDd8mWYcZu7b8g,
IsFault: True, FaultMessage: Status(StatusCode="InvalidArgument",
Detail="Request contains an invalid argument.")

বিস্তারিত লগ

GoogleAds.DetailedRequestLogs Verbose: 1 : [2023-11-02 21:09:36Z] -
---------------BEGIN API CALL---------------

Request
-------

Method Name: /google.ads.googleads.v26.services.GoogleAdsService/SearchStream
Host:
Headers: {
  "x-goog-api-client": "gl-dotnet/5.0.0 gapic/17.0.1 gax/4.2.0 grpc/2.46.3",
  "login-customer-id": "1234567890",
  "x-goog-request-params": "customer_id=4567890123"
}

{
  "customerId": "4567890123",
  "query": "SELECT ad_group_criterion.type FROM ad_group_criterion WHERE ad_group.status IN (ENABLED, PAUSED) AND campaign.status IN (ENABLED, PAUSED)",
  "summaryRowSetting": "NO_SUMMARY_ROW"
}

Response
--------
Headers: {
  "date": "Thu, 02 Nov 2023 21:09:35 GMT",
  "alt-svc": "h3-29=\":443\"; ma=2592000"
}

{
  "results": [
    {
      "adGroupCriterion": {
        "resourceName": "customers/4567890123/adGroupCriteria/456789456789~123456123467",
        "type": "KEYWORD"
      }
    },
    {
      "adGroupCriterion": {
        "resourceName": "customers/4567890123/adGroupCriteria/456789456789~56789056788",
        "type": "KEYWORD"
      }
    }
  ],
  "fieldMask": "adGroupCriterion.type",
  "requestId": "VsJ4F00ew6s9heHvAJ-abw"
}
----------------END API CALL----------------

আমি ক্লায়েন্ট লাইব্রেরি ব্যবহার না করলে কী হবে?

আপনি ক্লায়েন্ট লাইব্রেরি ব্যবহার না করলে, আউটগোয়িং ও ইনকামিং API কলের বিবরণ ক্যাপচার করতে আপনার নিজস্ব লগিং প্রয়োগ করুন। আপনাকে অন্তত request-id রেসপন্স হেডারের ভ্যালু লগ করতে হবে, যা পরে প্রয়োজন অনুযায়ী টেকনিক্যাল সাপোর্ট টিমের সাথে শেয়ার করা যেতে পারে।

ক্লাউডে লগ করা

আপনার অ্যাপ্লিকেশনের জন্য লগ ও পারফর্ম্যান্স মেট্রিক ক্যাপচার করতে আপনি অনেক টুল ব্যবহার করতে পারেন। যেমন, আপনার Google Cloud প্রোজেক্টে পারফর্ম্যান্স মেট্রিক লগ করতে Google Cloud Logging ব্যবহার করতে পারেন। এর ফলে, লগ করা মেট্রিক ব্যবহার করার জন্য Google Cloud Monitoring-এ ড্যাশবোর্ড ও সতর্কতা সেট-আপ করা সম্ভব হয়।

Cloud Logging, Perl ছাড়া Google Ads API ক্লায়েন্ট লাইব্রেরির সব ভাষার জন্য ক্লায়েন্ট লাইব্রেরি অফার করে, তাই বেশিরভাগ ক্ষেত্রে আপনার ক্লায়েন্ট লাইব্রেরি ইন্টিগ্রেশন থেকে সরাসরি Cloud Logging-এর মাধ্যমে লগ করা সম্ভব। Perl সহ অন্যান্য ভাষার জন্য, Cloud Logging-এ REST API-ও অফার করা হয়।

Google Ads API ক্লায়েন্ট লাইব্রেরি থেকে Cloud Logging বা অন্য কোনও টুলে লগ করার জন্য কয়েকটি বিকল্প আছে। প্রতিটি বিকল্পের নিজস্ব ট্রেড-অফ আছে, যেমন প্রয়োগ করার সময়, জটিলতা এবং পারফর্ম্যান্স। কোন সমাধানটি প্রয়োগ করবেন তা সিদ্ধান্ত নেওয়ার আগে এইসব ট্রেড-অফের ব্যাপারে ভাল করে ভেবে দেখুন।

বিকল্প ১: ব্যাকগ্রাউন্ড প্রসেস থেকে লোকাল লগ লেখা

আপনার লগিং কনফিগারেশন পরিবর্তন করে ক্লায়েন্ট লাইব্রেরি লগ আপনার মেশিনের লোকাল ফাইলে লেখা যেতে পারে। লগগুলি লোকাল ফাইলে আউটপুট করা হয়ে গেলে, আপনি লগ সংগ্রহ করে ক্লাউডে পাঠানোর জন্য একটি ডেমোন সেট-আপ করতে পারবেন।

এই পদ্ধতির একটি সীমাবদ্ধতা হল, কিছু পারফর্ম্যান্স মেট্রিক ডিফল্ট হিসেবে ক্যাপচার করা হবে না। ক্লায়েন্ট লাইব্রেরি লগে অনুরোধ ও উত্তর অবজেক্টের বিবরণ থাকে, তাই লেটেন্সি মেট্রিক অন্তর্ভুক্ত করা হবে না, যদি না এগুলিও লগ করার জন্য অতিরিক্ত পরিবর্তন করা হয়।

বিকল্প ২: Compute Engine এবং Ops Agent ব্যবহার করা

আপনার অ্যাপ্লিকেশন Compute Engine-এ রান করলে, Ops Agent ইনস্টল করে আপনি Google Cloud Logging-এ লগ পাঠাতে পারবেন। Ops Agent-কে কনফিগার করা যেতে পারে যাতে এটি Cloud Logging-এ আপনার অ্যাপ্লিকেশন লগ পাঠাতে পারে। এটি ডিফল্ট হিসেবে পাঠানো মেট্রিক ও লগ ছাড়াও করা হয়।

আপনার অ্যাপ্লিকেশন যদি আগে থেকেই Google Cloud এনভায়রনমেন্টে চলছে অথবা আপনি যদি Google Cloud-এ অ্যাপ্লিকেশন সরানোর কথা ভাবছেন, তাহলে এটি বিবেচনা করার জন্য একটি দারুণ বিকল্প হবে।

বিকল্প ৩: অ্যাপ্লিকেশন কোডে লগিং প্রয়োগ করা

অ্যাপ্লিকেশন কোড থেকে সরাসরি লগিং করার কাজ দুটি উপায়ের মধ্যে যেকোনও একটির মাধ্যমে করা যেতে পারে:

  1. আপনার কোডের প্রতিটি প্রযোজ্য লোকেশনে মেট্রিক গণনা এবং লগ স্টেটমেন্ট অন্তর্ভুক্ত করা। এই বিকল্পটি ছোট কোডবেসের জন্য আরও উপযুক্ত, যেখানে এই ধরনের পরিবর্তনের সুযোগ এবং রক্ষণাবেক্ষণের খরচ ন্যূনতম হবে।

  2. লগিং ইন্টারফেস প্রয়োগ করা। অ্যাপ্লিকেশন লজিককে যদি এমনভাবে অ্যাবস্ট্রাক্ট করা যায় যাতে অ্যাপ্লিকেশনের বিভিন্ন অংশ একই বেস ক্লাস থেকে ইনহেরিট করে, তাহলে সেই বেস ক্লাসে লগিং লজিক প্রয়োগ করা যেতে পারে। এই বিকল্পটি সাধারণত অ্যাপ্লিকেশন কোড জুড়ে লগ স্টেটমেন্ট অন্তর্ভুক্ত করার চেয়ে বেশি পছন্দ করা হয়, কারণ এটি বজায় রাখা এবং স্কেল করা সহজ। আরও বড় কোডবেসের জন্য, এই সমাধানের রক্ষণাবেক্ষণ ও স্কেলেবিলিটি আরও বেশি প্রাসঙ্গিক।

এই পদ্ধতির একটি সীমাবদ্ধতা হল যে সম্পূর্ণ অনুরোধ এবং প্রতিক্রিয়া লগ অ্যাপ্লিকেশন কোড থেকে পাওয়া যায় না। সম্পূর্ণ অনুরোধ ও উত্তর অবজেক্ট gRPC ইন্টারসেপ্টর থেকে অ্যাক্সেস করা যায়; বিল্ট-ইন ক্লায়েন্ট লাইব্রেরি লগিং এইভাবেই অনুরোধ ও উত্তর লগ পায়। কোনও সমস্যা হলে, এক্সেপশন অবজেক্টে অতিরিক্ত তথ্য উপলভ্য থাকতে পারে, তবে অ্যাপ্লিকেশন লজিকের মধ্যে সফল উত্তরের জন্য কম বিবরণ উপলভ্য থাকে। যেমন, বেশিরভাগ ক্ষেত্রে, সফল অনুরোধের জন্য অনুরোধ আইডি Google Ads API রেসপন্স অবজেক্ট থেকে অ্যাক্সেস করা যায় না।

বিকল্প ৪: কাস্টম gRPC লগিং ইন্টারসেপ্টর

gRPC ইউনারি ও স্ট্রিমিং ইন্টারসেপ্টর সাপোর্ট করে যা ক্লায়েন্ট ও সার্ভারের মধ্যে পাস করার সময় অনুরোধ ও উত্তর অবজেক্ট অ্যাক্সেস করতে পারে। Google Ads API ক্লায়েন্ট লাইব্রেরি gRPC ইন্টারসেপ্টর ব্যবহার করে বিল্ট-ইন লগিং সাপোর্ট অফার করে। একইভাবে, আপনি অনুরোধ ও উত্তর অবজেক্ট অ্যাক্সেস করতে, লগিং ও মনিটরিংয়ের উদ্দেশ্যে তথ্য এক্সট্র্যাক্ট করতে এবং আপনার পছন্দের লোকেশনে সেই ডেটা লিখতে কাস্টম gRPC ইন্টারসেপ্টর প্রয়োগ করতে পারেন।

এখানে দেখানো অন্যান্য সমাধানের মতো নয়, কাস্টম gRPC ইন্টারসেপ্টর প্রয়োগ করলে, প্রতিটি অনুরোধে অনুরোধ ও উত্তর অবজেক্ট ক্যাপচার করার এবং অনুরোধের বিবরণ ক্যাপচার করার জন্য অতিরিক্ত লজিক প্রয়োগ করার ক্ষেত্রে আপনি নমনীয়তা পাবেন। যেমন, কাস্টম ইন্টারসেপ্টরের মধ্যে পারফর্ম্যান্স টাইমিং লজিক প্রয়োগ করে আপনি কোনও অনুরোধের অতিবাহিত সময় গণনা করতে পারেন, তারপর Google Cloud Logging-এ মেট্রিক লগ করে Google Cloud Monitoring-এর মধ্যে লেটেন্সি মনিটরিংয়ের জন্য এটি উপলভ্য করতে পারেন।

Python-এ কাস্টম Cloud Logging ইন্টারসেপ্টর

এই সমাধানটি দেখানোর জন্য, আমরা Python-এ একটি কাস্টম লগিং ইন্টারসেপ্টরের উদাহরণ লিখেছি। কাস্টম ইন্টারসেপ্টর তৈরি করা হয় এবং পরিষেবা ক্লায়েন্টে পাস করা হয়। তারপরে, এটি প্রতিটি পরিষেবা পদ্ধতি কলের মাধ্যমে পাস করা অনুরোধ এবং উত্তর অবজেক্ট অ্যাক্সেস করে, সেইসব অবজেক্ট থেকে ডেটা প্রসেস করে এবং Google Cloud Logging-এ ডেটা পাঠায়।

অনুরোধ ও উত্তর অবজেক্ট থেকে পাওয়া ডেটা ছাড়াও, অনুরোধের অতিবাহিত সময় এবং অন্যান্য মেটাডেটা ক্যাপচার করার জন্য এই উদাহরণে কিছু অতিরিক্ত লজিক প্রয়োগ করা হয়েছে। এগুলি মনিটরিংয়ের উদ্দেশ্যে সহায়ক হবে। যেমন, অনুরোধটি সফল হয়েছে কিনা। এই তথ্য কীভাবে কাজে লাগতে পারে, সাধারণভাবে মনিটর করার জন্য এবং বিশেষভাবে Google Cloud Logging ও Google Cloud Monitoring একসাথে ব্যবহার করার সময়, সেই সম্পর্কে আরও জানতে মনিটর করার গাইড দেখুন।

# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A custom gRPC Interceptor that logs requests and responses to Cloud Logging.

The custom interceptor object is passed into the get_service method of the
GoogleAdsClient. It intercepts requests and responses, parses them into a
human readable structure and logs them using the logging service instantiated
within the class (in this case, a Cloud Logging client).
"""

import time
from typing import Any, Callable, Dict, Optional

from google.cloud import logging as google_cloud_logging
from grpc._interceptor import _ClientCallDetails

from google.ads.googleads.interceptors import LoggingInterceptor


class CloudLoggingInterceptor(LoggingInterceptor):
    """An interceptor that logs rpc request and response details to Google Cloud Logging.

    This class inherits logic from the LoggingInterceptor, which simplifies the
    implementation here. Some logic is required here in order to make the
    underlying logic work -- comments make note of this where applicable.
    NOTE: Inheriting from the LoggingInterceptor class could yield unexpected side
    effects. For example, if the LoggingInterceptor class is updated, this class would
    inherit the updated logic, which could affect its functionality. One option to avoid
    this is to inherit from the Interceptor class instead, and selectively copy whatever
    logic is needed from the LoggingInterceptor class."""

    def __init__(self, api_version: str):
        """Initializer for the CloudLoggingInterceptor.

        Args:
            api_version: a str of the API version of the request.
        """
        super().__init__(logger=None, api_version=api_version)
        # Instantiate the Cloud Logging client.
        logging_client: google_cloud_logging.Client = google_cloud_logging.Client()
        self.logger: google_cloud_logging.Logger = logging_client.logger("cloud_logging")
        self.rpc_start: float
        self.rpc_end: float

    def log_successful_request(
        self,
        method: str,
        customer_id: Optional[str],
        metadata_json: str,
        request_id: str,
        request: Any,  # google.ads.googleads.vX.services.types.SearchGoogleAdsRequest or SearchGoogleAdsStreamRequest
        trailing_metadata_json: str,
        response: Any,  # grpc.Call or grpc.Future
    ) -> None:
        """Handles logging of a successful request.

        Args:
            method: The method of the request.
            customer_id: The customer ID associated with the request.
            metadata_json: A JSON str of initial_metadata.
            request_id: A unique ID for the request provided in the response.
            request: An instance of a request proto message.
            trailing_metadata_json: A JSON str of trailing_metadata.
            response: A grpc.Call/grpc.Future instance.
        """
        # Retrieve and mask the RPC result from the response future.
        # This method is available from the LoggingInterceptor class.
        # Ensure self._cache is set in order for this to work.
        # The response result could contain up to 10,000 rows of data,
        # so consider truncating this value before logging it, to save
        # on data storage costs and maintain readability.
        result: Any = self.retrieve_and_mask_result(response)

        # elapsed_ms is the approximate elapsed time of the RPC, in milliseconds.
        # There are different ways to define and measure elapsed time, so use
        # whatever approach makes sense for your monitoring purposes.
        # rpc_start and rpc_end are set in the intercept_unary_* methods below.
        elapsed_ms: float = (self.rpc_end - self.rpc_start) * 1000

        debug_log: Dict[str, Any] = {
            "method": method,
            "host": metadata_json,
            "request_id": request_id,
            "request": str(request),
            "headers": trailing_metadata_json,
            "response": str(result),
            "is_fault": False,
            "elapsed_ms": elapsed_ms,
        }
        self.logger.log_struct(debug_log, severity="DEBUG")

        info_log: Dict[str, Any] = {
            "customer_id": customer_id,
            "method": method,
            "request_id": request_id,
            "is_fault": False,
            # Available from the Interceptor class.
            "api_version": self._api_version,
        }
        self.logger.log_struct(info_log, severity="INFO")

    def log_failed_request(
        self,
        method: str,
        customer_id: Optional[str],
        metadata_json: str,
        request_id: str,
        request: Any,  # google.ads.googleads.vX.services.types.SearchGoogleAdsRequest or SearchGoogleAdsStreamRequest
        trailing_metadata_json: str,
        response: Any,  # grpc.Call or grpc.Future
    ) -> None:
        """Handles logging of a failed request.

        Args:
            method: The method of the request.
            customer_id: The customer ID associated with the request.
            metadata_json: A JSON str of initial_metadata.
            request_id: A unique ID for the request provided in the response.
            request: An instance of a request proto message.
            trailing_metadata_json: A JSON str of trailing_metadata.
            response: A JSON str of the response message.
        """
        exception: Any = self._get_error_from_response(response)
        exception_str: str = self._parse_exception_to_str(exception)
        fault_message: str = self._get_fault_message(exception)

        info_log: Dict[str, Any] = {
            "method": method,
            "endpoint": self.endpoint,
            "host": metadata_json,
            "request_id": request_id,
            "request": str(request),
            "headers": trailing_metadata_json,
            "exception": exception_str,
            "is_fault": True,
        }
        self.logger.log_struct(info_log, severity="INFO")

        error_log: Dict[str, Any] = {
            "method": method,
            "endpoint": self.endpoint,
            "request_id": request_id,
            "customer_id": customer_id,
            "is_fault": True,
            "fault_message": fault_message,
        }
        self.logger.log_struct(error_log, severity="ERROR")

    def intercept_unary_unary(
        self,
        continuation: Callable[[_ClientCallDetails, Any], Any], # Any is request type
        client_call_details: _ClientCallDetails,
        request: Any,  # google.ads.googleads.vX.services.types.SearchGoogleAdsRequest
    ) -> Any:  # grpc.Call or grpc.Future
        """Intercepts and logs API interactions.

        Overrides abstract method defined in grpc.UnaryUnaryClientInterceptor.

        Args:
            continuation: a function to continue the request process.
            client_call_details: a grpc._interceptor._ClientCallDetails
                instance containing request metadata.
            request: a SearchGoogleAdsRequest or SearchGoogleAdsStreamRequest
                message class instance.

        Returns:
            A grpc.Call/grpc.Future instance representing a service response.
        """
        # Set the rpc_end value to current time when RPC completes.
        def update_rpc_end(response_future: Any) -> None: # response_future is grpc.Future
            self.rpc_end = time.perf_counter()

        # Capture precise clock time to later calculate approximate elapsed
        # time of the RPC.
        self.rpc_start = time.perf_counter()

        # The below call is REQUIRED.
        response: Any = continuation(client_call_details, request) # response is grpc.Call or grpc.Future

        response.add_done_callback(update_rpc_end)

        self.log_request(client_call_details, request, response)

        # The below return is REQUIRED.
        return response

    def intercept_unary_stream(
        self,
        continuation: Callable[[_ClientCallDetails, Any], Any], # Any is request type
        client_call_details: _ClientCallDetails,
        request: Any,  # google.ads.googleads.vX.services.types.SearchGoogleAdsStreamRequest
    ) -> Any:  # grpc.Call or grpc.Future
        """Intercepts and logs API interactions for Unary-Stream requests.

        Overrides abstract method defined in grpc.UnaryStreamClientInterceptor.

        Args:
            continuation: a function to continue the request process.
            client_call_details: a grpc._interceptor._ClientCallDetails
                instance containing request metadata.
            request: a SearchGoogleAdsRequest or SearchGoogleAdsStreamRequest
                message class instance.

        Returns:
            A grpc.Call/grpc.Future instance representing a service response.
        """

        def on_rpc_complete(response_future: Any) -> None: # response_future is grpc.Future
            self.rpc_end = time.perf_counter()
            self.log_request(client_call_details, request, response_future)

        # Capture precise clock time to later calculate approximate elapsed
        # time of the RPC.
        self.rpc_start = time.perf_counter()

        # The below call is REQUIRED.
        response: Any = continuation(client_call_details, request) # response is grpc.Call or grpc.Future

        # Set self._cache to the cache on the response wrapper in order to
        # access the streaming logs. This is REQUIRED in order to log streaming
        # requests.
        self._cache = response.get_cache()

        response.add_done_callback(on_rpc_complete)

        # The below return is REQUIRED.
        return response