लॉग इन हो रहा है

ऐप्लिकेशन की परफ़ॉर्मेंस को समझने और उसे ऑप्टिमाइज़ करने के साथ-साथ गड़बड़ियों और सिस्टम से जुड़ी समस्याओं की पहचान करने के लिए, एक साथ कई लॉग और मॉनिटर करना. आपको सभी एपीआई कॉल के लिए खास जानकारी लॉग की सुविधा चालू करनी चाहिए. साथ ही, पूरे न हो पाने वाले एपीआई कॉल के लिए, ज़्यादा जानकारी वाले लॉग चालू करने चाहिए. इससे तकनीकी सहायता की ज़रूरत होने पर, एपीआई कॉल लॉग उपलब्ध कराए जा सकेंगे.

क्लाइंट लाइब्रेरी में लॉग इकट्ठा करने की सुविधा

Google Ads API की क्लाइंट लाइब्रेरी में पहले से ही लॉग इन करने की सुविधा होती है. अलग-अलग प्लैटफ़ॉर्म के हिसाब से लॉग करने की जानकारी के लिए, अपनी पसंद की क्लाइंट लाइब्रेरी में मौजूद लॉगिंग दस्तावेज़ देखें.

Language गाइड
Java Java के लिए दस्तावेज़ लॉग करना
.NET .NET के लिए दस्तावेज़ों को लॉग करना
PHP PHP के लिए दस्तावेज़ों को लॉग करना
Python Python के लिए दस्तावेज़ लॉग करना
Ruby Ruby के लिए दस्तावेज़ लॉग करना
Perl पर्ल के लिए दस्तावेज़ लॉग करना

लॉग फ़ॉर्मैट

Google Ads API क्लाइंट लाइब्रेरी, हर एपीआई कॉल के लिए ज़्यादा जानकारी वाला लॉग और खास जानकारी वाला लॉग जनरेट करती है. ज़्यादा जानकारी वाले लॉग में एपीआई कॉल की पूरी जानकारी होती है, जबकि खास जानकारी वाले लॉग में एपीआई कॉल की कम से कम जानकारी होती है. हर तरह के लॉग का एक उदाहरण दिखाया गया है. इसमें लॉग छोटे किए गए हैं और इन्हें पढ़ने लायक बनाने के लिए फ़ॉर्मैट किया गया है.

खास जानकारी का लॉग

GoogleAds.SummaryRequestLogs Warning: 1 : [2023-09-15 19:58:39Z] -
Request made: Host: , Method: /google.ads.googleads.v14.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.v14.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 gccl/3.0.1 pb/3.21.5",
  "developer-token": "REDACTED",
  "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----------------

अगर मैं क्लाइंट लाइब्रेरी का इस्तेमाल न करूं, तो क्या होगा?

अगर क्लाइंट लाइब्रेरी का इस्तेमाल नहीं किया जाता है, तो आउटगोइंग और इनकमिंग एपीआई कॉल की जानकारी को कैप्चर करने के लिए, अपना लॉग इन करें. आपको कम से कम request-id रिस्पॉन्स हेडर की वैल्यू लॉग करनी चाहिए. इसे ज़रूरत के मुताबिक, तकनीकी सहायता टीम के साथ शेयर किया जा सकता है.

क्लाउड में लॉग इन किया जा रहा है

अपने ऐप्लिकेशन के लॉग और परफ़ॉर्मेंस मेट्रिक को कैप्चर करने के लिए, कई टूल का इस्तेमाल किया जा सकता है. उदाहरण के लिए, अपने Google Cloud प्रोजेक्ट में परफ़ॉर्मेंस मेट्रिक का लॉग बनाने के लिए, Google Cloud Logging का इस्तेमाल किया जा सकता है. इससे, लॉग की गई मेट्रिक का इस्तेमाल करने के लिए, डैशबोर्ड सेट अप किए जा सकते हैं और Google Cloud मॉनिटरिंग में सूचना दी जा सकती है.

Cloud Logging, Perl के अलावा, अन्य सभी Google Ads API क्लाइंट लाइब्रेरी भाषाओं के लिए क्लाइंट लाइब्रेरी की सुविधा देता है जिनका इस्तेमाल Google Ads API की क्लाइंट लाइब्रेरी के लिए किया जाता है. इसलिए, ज़्यादातर मामलों में, सीधे क्लाइंट लाइब्रेरी इंटिग्रेशन से Cloud Logging के साथ लॉग इन किया जा सकता है. Perl जैसी अन्य भाषाओं के लिए, क्लाउड लॉगिंग एक REST API भी ऑफ़र करती है.

आपके पास Google Ads API क्लाइंट लाइब्रेरी से, क्लाउड लॉगिंग या किसी दूसरे टूल में लॉग इन करने के कुछ विकल्प हैं. हर विकल्प को लागू करने, जटिलता, और परफ़ॉर्मेंस को बेहतर बनाने में ज़्यादा समय लगता है. कौनसा समाधान लागू करना है, यह तय करने से पहले, इन ट्रेड-ऑफ़ के बारे में सोच-समझकर फ़ैसला लें.

पहला विकल्प: बैकग्राउंड में चल रही प्रोसेस के ज़रिए, क्लाउड पर लोकल लॉग लिखना

आपके लॉगिंग कॉन्फ़िगरेशन को बदलकर क्लाइंट लाइब्रेरी लॉग को आपकी मशीन पर किसी स्थानीय फ़ाइल में लिखा जा सकता है. जब लॉग किसी लोकल फ़ाइल में आउटपुट हो जाते हैं, तो लॉग इकट्ठा करने और उन्हें क्लाउड पर भेजने के लिए डीमन सेट किया जा सकता है.

इस तरीके की एक सीमा यह है कि कुछ परफ़ॉर्मेंस मेट्रिक डिफ़ॉल्ट रूप से कैप्चर नहीं की जातीं. क्लाइंट लाइब्रेरी के लॉग में, अनुरोध और रिस्पॉन्स ऑब्जेक्ट की जानकारी शामिल होती है. इसलिए, इंतज़ार के समय वाली मेट्रिक को तब तक शामिल नहीं किया जाएगा, जब तक इन्हें लॉग करने में और बदलाव न किए जाएं.

विकल्प 2: Compute Engine पर अपना ऐप्लिकेशन चलाएं और ऑपरेशन एजेंट इंस्टॉल करें

अगर आपका ऐप्लिकेशन Compute Engine पर चल रहा है, तो आपके पास Ops एजेंट इंस्टॉल करके, Google 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 मॉनिटरिंग में इंतज़ार के समय के लिए उपलब्ध कराया जा सके.

Python में, कस्टम Google क्लाउड लॉगिंग इंटरसेप्टर

यह हल दिखाने के लिए, हमने Python में कस्टम लॉगिंग इंटरसेप्टर का एक उदाहरण दिया है. कस्टम इंटरसेप्टर बनाया जाता है और सेवा क्लाइंट को भेजा जाता है. इसके बाद यह अनुरोध और रिस्पॉन्स ऑब्जेक्ट को ऐक्सेस करता है जो हर सेवा तरीके के कॉल को पास करते हैं, उन ऑब्जेक्ट से डेटा प्रोसेस करते हैं, और डेटा को Google क्लाउड लॉगिंग पर भेजते हैं.

अनुरोध और रिस्पॉन्स ऑब्जेक्ट से मिलने वाले डेटा के अलावा, उदाहरण में अनुरोध के लिए बीते समय को कैप्चर करने के लिए कुछ अतिरिक्त लॉजिक लागू किया गया है. साथ ही, कुछ अन्य मेटाडेटा भी लागू किया गया है जो निगरानी के मकसद से मददगार होंगे. जैसे, अनुरोध पूरा हुआ या नहीं. यह जानकारी किस तरह काम की हो सकती है, इस बारे में ज़्यादा जानने के लिए मॉनिटरिंग गाइड पढ़ें. इसमें आम तौर पर निगरानी करने और खास तौर पर 'Google क्लाउड लॉगिंग' और 'Google क्लाउड मॉनिटरिंग' को साथ मिलाकर इस्तेमाल करने के बारे में बताया गया है.

# 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 logging
import time

from google.cloud import logging
from grpc import UnaryUnaryClientInterceptor, UnaryStreamClientInterceptor

from google.ads.googleads.interceptors import LoggingInterceptor, mask_message


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):
        """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 = logging.Client()
        self.logger = logging_client.logger("cloud_logging")

    def log_successful_request(
        self,
        method,
        customer_id,
        metadata_json,
        request_id,
        request,
        trailing_metadata_json,
        response,
    ):
        """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 = 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 = (self.rpc_end - self.rpc_start) * 1000

        debug_log = {
            "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 = {
            "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,
        customer_id,
        metadata_json,
        request_id,
        request,
        trailing_metadata_json,
        response,
    ):
        """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 = self._get_error_from_response(response)
        exception_str = self._parse_exception_to_str(exception)
        fault_message = self._get_fault_message(exception)

        info_log = {
            "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 = {
            "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, client_call_details, request):
        """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):
            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 = continuation(client_call_details, request)

        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, client_call_details, request
    ):
        """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):
            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 = continuation(client_call_details, request)

        # 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