Get a list of log names from the Google Cloud Stackdriver API using Python

I use the Google Stackdriver Logging Client Libraries for Python to programmatically retrieve log entries , similar to using gcloud beta logging read.

Stackdriver also provides an API for retrieving a list of log names , which is most likely used gcloud beta logging logs list.

How can I use this API with Python client libraries? I did not find anything in the docs .

+4
source share
1 answer

Stackdriver Logging Client Libraries Python. pip install --upgrade google-cloud-logging, , โ€‹โ€‹ , .

, , :


, , , :

# Import the Google Cloud Python client library
from google.cloud import logging
from google.cloud.logging import DESCENDING

# Instantiate a client
logging_client = logging.Client(project = "<YOUR_PROJECT_ID>")

# Set the filter to apply to the logs
FILTER = 'resource.type:gae_app and resource.labels.module_id:default and severity>=WARNING'

i = 0 
# List the entries in DESCENDING order and applying the FILTER
for entry in logging_client.list_entries(order_by=DESCENDING, filter_=FILTER):  # API call
    print('{} - Severity: {}'.format(entry.timestamp, entry.severity))
    if (i >= 5):
        break
    i += 1

, ( , YOUR_PROJECT_ID), , WARNING , , 6 .

:

my-console:python/logs$ python example_log.py
2018-01-25 09:57:51.524603+00:00 - Severity: ERROR
2018-01-25 09:57:44.696807+00:00 - Severity: WARNING
2018-01-25 09:57:44.661957+00:00 - Severity: ERROR
2018-01-25 09:57:37.948483+00:00 - Severity: WARNING
2018-01-25 09:57:19.632910+00:00 - Severity: ERROR
2018-01-25 09:54:39.334199+00:00 - Severity: ERROR

, , ( , ):

enter image description here

, ( , ) Stackdriver Python.


@otto.poellath, , . Python, API Python ( , Python). pip install --upgrade google-api-python-client, REST API (, , ), Python. , , ( ) , API REST. , :

from apiclient.discovery import build
from oauth2client.client import GoogleCredentials
import json

credentials = GoogleCredentials.get_application_default()
service = build('logging', 'v2', credentials=credentials)

# Methods available in: https://developers.google.com/resources/api-libraries/documentation/logging/v2/python/latest/index.html
collection = service.logs()

# Build the request and execute it
request = collection.list(parent='projects/<YOUR_PROJECT_ID>')
res = request.execute()

print(json.dumps(res, sort_keys=True, indent=4))

, :

my-console:python/logs$ python list_logs.py
{
    "logNames": [
        "projects/<YOUR_PROJECT_ID>/logs/my-log",
        "projects/<YOUR_PROJECT_ID>/logs/my-test-log",
        "projects/<YOUR_PROJECT_ID>/logs/python",
        "projects/<YOUR_PROJECT_ID>/logs/requests"
    ]
}

, , , Python , , , , , , Python.

+3

Source: https://habr.com/ru/post/1683975/


All Articles