Skip to content

Commit bd3d8fc

Browse files
chore(docs): added audit log sample to usage guide (#428)
1 parent 007a9ef commit bd3d8fc

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

logging/samples/snippets/usage_guide.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,33 @@ def client_list_entries(client, to_delete): # pylint: disable=unused-argument
7171
# [END client_list_entries_order_by]
7272
break
7373

74+
# [START logging_list_gke_audit_logs]
75+
import google.cloud.logging
76+
from datetime import datetime, timedelta, timezone
77+
import os
78+
79+
# pull your project id from an environment variable
80+
project_id = os.environ["GOOGLE_CLOUD_PROJECT"]
81+
# construct a date object representing yesterday
82+
yesterday = datetime.now(timezone.utc) - timedelta(days=1)
83+
# Cloud Logging expects a timestamp in RFC3339 UTC "Zulu" format
84+
# https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
85+
time_format = "%Y-%m-%dT%H:%M:%S.%f%z"
86+
# build a filter that returns GKE Admin Activity audit Logs from
87+
# the past 24 hours
88+
# https://cloud.google.com/kubernetes-engine/docs/how-to/audit-logging
89+
filter_str = (
90+
f'logName="projects/{project_id}/logs/cloudaudit.googleapis.com%2Factivity"'
91+
f' AND resource.type="k8s_cluster"'
92+
f' AND timestamp>="{yesterday.strftime(time_format)}"'
93+
)
94+
# query and print all matching logs
95+
client = google.cloud.logging.Client()
96+
for entry in client.list_entries(filter_=filter_str):
97+
print(entry)
98+
# [END logging_list_gke_audit_logs]
99+
break # we don't really need to print them all
100+
74101

75102
@snippet
76103
def logger_usage(client, to_delete):

0 commit comments

Comments
 (0)