Menginstrumentasikan aplikasi Python untuk Error Reporting

Anda dapat mengirim peristiwa error ke Error Reporting dari aplikasi Python menggunakan library Error Reporting untuk Python. Gunakan library Error Reporting untuk Python guna membuat grup error untuk kasus berikut:

  • Bucket log yang berisi entri log Anda memiliki kunci enkripsi yang dikelola pelanggan (CMEK).
  • Bucket log memenuhi salah satu hal berikut:
    • Bucket log disimpan di project yang sama dengan tempat asal entri log.
    • Entri log dirutekan ke project, lalu project tersebut menyimpan entri log tersebut di bucket log yang dimilikinya.
  • Anda ingin melaporkan peristiwa error kustom.

Error Reporting terintegrasi dengan beberapa Google Cloud layanan, seperti Cloud Run Functions dan App Engine, Compute Engine, serta Google Kubernetes Engine. Error Reporting menampilkan peristiwa error yang dicatat ke Cloud Logging oleh aplikasi yang berjalan di layanan tersebut. Untuk mengetahui informasi selengkapnya, buka Menjalankan Google Cloud di halaman ini.

Anda juga dapat mengirim peristiwa error ke Error Reporting menggunakan Logging. Untuk mengetahui informasi tentang persyaratan pemformatan data, baca Memformat entri log untuk melaporkan peristiwa error.

Sebelum memulai

  1. Login keakun Anda. Google Cloud Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa produk kami dalam skenario dunia nyata. Pelanggan baru juga mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Error Reporting API .

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Error Reporting API .

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  8. Siapkan lingkungan Anda untuk pengembangan Python.

    Buka panduan penyiapan Python

Menginstal library klien

Library Error Reporting untuk Python memungkinkan Anda memantau dan melihat peristiwa error yang dilaporkan oleh aplikasi Python yang berjalan hampir di mana saja.

  1. Buat instance lingkungan virtual dan gunakan pip untuk menginstal paket:

    pip install google-cloud-error-reporting --upgrade
    
  2. Impor library dan buat instance klien untuk mulai melaporkan error:

    Python

    Untuk melakukan autentikasi ke Error Reporting, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

    #!/usr/bin/env python
    #
    # Copyright 2022 Google, Inc.
    #
    # 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
    #
    #    http://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.
    
    
    def report_exception():
        from google.cloud import error_reporting
    
        client = error_reporting.Client()
        try:
            raise Exception("Something went wrong")
        except Exception:
            client.report_exception()
    
    
    
    
    def report_manual_error():
        from google.cloud import error_reporting
    
        client = error_reporting.Client()
        client.report("An error has occurred.")
    
    
    
    
    if __name__ == "__main__":
        report_exception()
        report_manual_error()
    

Untuk mengetahui informasi selengkapnya tentang penginstalan, baca dokumentasi untuk library Error Reporting untuk Python. Anda juga dapat melaporkan masalah menggunakan the issue tracker.

Mengonfigurasi library klien

Anda dapat menyesuaikan perilaku library Error Reporting untuk Python. Lihat dokumentasi library klien untuk contoh konfigurasi.

Menjalankan aplikasi di Google Cloud

Untuk membuat grup error menggunakan projects.events.report, akun layanan Anda memerlukan peran Penulis Error Reporting (roles/errorreporting.writer).

Beberapa Google Cloud layanan secara otomatis memberikan peran Penulis Error Reporting (roles/errorreporting.writer) ke akun layanan yang sesuai. Namun, Anda harus memberikan peran ini ke akun layanan yang sesuai untuk beberapa layanan.

Cloud Run dan Cloud Run Functions

Akun layanan default yang digunakan oleh Cloud Run memiliki izin peran Penulis Error Reporting (roles/errorreporting.writer).

Library Error Reporting untuk Python dapat digunakan tanpa perlu memberikan kredensial secara eksplisit.

Cloud Run dikonfigurasi untuk menggunakan Error Reporting secara otomatis. Pengecualian JavaScript yang tidak tertangani akan muncul di Logging dan diproses oleh Error Reporting tanpa perlu menggunakan library Error Reporting untuk Python.

Lingkungan fleksibel App Engine

App Engine secara otomatis memberikan peran Penulis Error Reporting (roles/errorreporting.writer) ke akun layanan default Anda.

Library Error Reporting untuk Python dapat digunakan tanpa perlu memberikan kredensial secara eksplisit.

Error Reporting diaktifkan secara otomatis untuk aplikasi lingkungan fleksibel App Engine. Tidak diperlukan penyiapan tambahan.

Google Kubernetes Engine

Untuk menggunakan Error Reporting dengan Google Kubernetes Engine, lakukan hal berikut:

  1. Pastikan akun layanan yang akan digunakan oleh container Anda telah diberi peran Penulis Error Reporting (roles/errorreporting.writer).

    Anda dapat menggunakan akun layanan default Compute Engine atau akun layanan kustom.

    Untuk mengetahui informasi tentang cara memberikan peran, lihat Mengelola akses ke project, folder, dan organisasi.

  2. Buat cluster Anda dan berikan cakupan akses cloud-platform ke cluster.

    Misalnya, perintah pembuatan berikut menentukan cakupan akses cloud-platform dan akun layanan:

    gcloud container clusters create CLUSTER_NAME --service-account  SERVICE_ACCT_NAME --scopes=cloud-platform
    

Compute Engine

Untuk menggunakan Error Reporting dengan instance VM Compute Engine, lakukan hal berikut:

  1. Pastikan akun layanan yang akan digunakan oleh instance VM Anda telah diberi peran Penulis Error Reporting (roles/errorreporting.writer).

    Anda dapat menggunakan akun layanan default Compute Engine atau akun layanan kustom.

    Untuk mengetahui informasi tentang cara memberikan peran, lihat Mengelola akses ke project, folder, dan organisasi.

  2. Di Google Cloud konsol, buka halaman VM instances:

    Buka VM instances

    Jika Anda menggunakan kotak penelusuran untuk menemukan halaman ini, pilih hasil yang subjudulnya adalah Compute Engine.

  3. Pilih instance VM yang ingin Anda beri cakupan akses cloud-platform .

  4. Klik Stop, lalu klik Edit.

  5. Di bagian Identity and API access, pilih akun layanan yang memiliki peran Penulis Error Reporting (roles/errorreporting.writer).

  6. Di bagian Access scopes , pilih Allow full access to all Cloud APIs, lalu simpan perubahan Anda.

  7. Klik Start/Resume.

Contoh

Anda dapat melaporkan error secara manual dengan memanggil metode report, seperti yang terlihat dalam contoh berikut:

Python

Untuk melakukan autentikasi ke Error Reporting, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi.

#!/usr/bin/env python
#
# Copyright 2022 Google, Inc.
#
# 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
#
#    http://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.


def report_exception():
    from google.cloud import error_reporting

    client = error_reporting.Client()
    try:
        raise Exception("Something went wrong")
    except Exception:
        client.report_exception()




def report_manual_error():
    from google.cloud import error_reporting

    client = error_reporting.Client()
    client.report("An error has occurred.")




if __name__ == "__main__":
    report_exception()
    report_manual_error()

Menjalankan aplikasi di lingkungan pengembangan lokal

Untuk menggunakan library Error Reporting untuk Python di lingkungan pengembangan lokal, seperti menjalankan library di workstation Anda sendiri, Anda harus memberikan kredensial default aplikasi lokal ke library Error Reporting untuk Python. Untuk mengetahui informasi selengkapnya, lihat Mengautentikasi ke Error Reporting.

Untuk menggunakan contoh Python di halaman ini dalam lingkungan pengembangan lokal, instal dan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

  1. Instal Google Cloud CLI.

  2. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus terlebih dahulu login ke gcloud CLI dengan identitas gabungan Anda.

  3. Jika Anda menggunakan shell lokal, buat kredensial autentikasi lokal untuk akun pengguna Anda:

    gcloud auth application-default login

    Anda tidak perlu melakukan hal ini jika menggunakan Cloud Shell.

    Jika error autentikasi ditampilkan, dan Anda menggunakan penyedia identitas (IdP) eksternal, pastikan Anda telah login ke gcloud CLI dengan identitas gabungan Anda.

Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

Metode projects.events.report juga mendukung kunci API. Jika ingin menggunakan kunci API untuk autentikasi, Anda tidak perlu menyiapkan file Kredensial Default Aplikasi lokal. Untuk mengetahui informasi selengkapnya, lihat Membuat kunci API di Google Cloud dokumentasi autentikasi.

Melihat grup error

Di Google Cloud konsol, buka halaman Error Reporting:

Buka Error Reporting

Anda juga dapat menemukan halaman ini menggunakan kotak penelusuran.

Untuk mengetahui informasi selengkapnya, lihat Melihat dan memfilter grup error.