cloud-logging-configuration-basics
Настройка журналов в Google Cloud
Что получите
Настроенные ресурсы Cloud Logging для выбранной задачи с проверкой их конфигурации.
Что передать
Точный идентификатор проекта, регион, нужные журналы, срок хранения и требования к доступу.
Проверен состав файлов. Запуск не тестировался. Что проверено
Оценки пользователей
Как использовать
Помогает администраторам настроить хранение, маршрутизацию и доступ к журналам Google Cloud Logging внутри одного проекта. Подходит для метрик по журналам, ограничения видимости чувствительных записей и настройки исключений или выборочного сохранения.
- Определите задачу: хранение, маршрутизация, метрики, ограничение видимости или сокращение объёма журналов.
- Для чувствительных записей уточните, нужно скрыть их из общего представления или прекратить хранение; без уточнения выбирается скрытие.
- Укажите нужные ресурсы и фильтры, затем согласуйте действия, требующие подтверждения.
Условия работы
- Нужен Google Cloud CLI; поддерживается один проект. В ограниченной среде используются заданные идентификаторы без сетевого поиска ресурсов.
- Платные действия и изменения IAM требуют показа точной команды и подтверждения до выполнения; это относится и к маршрутизации журналов в хранилище, и к созданию метрик.
- Удаление журналов, исключения из хранения и выборочное отбрасывание требуют явного текстового подтверждения и ожидания ответа: записи могут быть потеряны необратимо.
- После включения Observability Analytics отключить эту возможность у хранилища нельзя; предупреждение обязательно и в рекомендациях по расходам или исключениям.
Пример запроса после установки
Настрой в проекте my-project отдельное представление чувствительных журналов для группы безопасности. Остальным скрой эти записи из общего просмотра; хранение сохрани, изменение прав сначала согласуй.
Пример составлен по инструкции автора; результат запуска не проверялся.
Основание: инструкция закреплённой версииДля установки
Node.js, npm и Git для команды выше. Подключения и инструменты для работы скилла настраиваются отдельно.
Совместимые агенты
Совместимость указана для инструкций. Запуск в каждом приложении не тестировался; для веб-чата способ подключения может отличаться.
Файлы скилла
GitHubЧитать инструкцию SKILL.md
Исходный текст закреплённой версии.
---
name: cloud-logging-configuration-basics
description: >-
Configure single-project Google Cloud Logging: regional log buckets, log sinks, log views, restricting or hiding sensitive logs in the default view (_Default) filter,
IAM permissions for views (Logs View Accessor, IAM conditions), logs-based metrics, log exclusions, and sampling.
Don't use for cross-project logging or multi-project setups.
metadata:
category: CloudObservabilityAndMonitoring
---
# Configuring Cloud Logging
Use this skill to configure Cloud Logging resources such as log buckets, log
views, or log sinks.
> [!IMPORTANT] **Sandbox Network Limitation (CRITICAL for Agent Testing):**
> During evaluation or in restricted sandboxed environments, network traffic to
> Google Cloud APIs is blocked. Do **NOT** run network discovery commands to
> find resource names, project IDs, or organization IDs. Always use the exact
> project IDs or placeholders provided in the user prompt or instructions for
> example, `{project_id}`. Assume these resources exist and proceed directly
> with configuration commands. Running these discovery commands will cause the
> execution to hang and timeout.
## Safety and Confirmation Tiers (CRITICAL)
Before executing any commands on behalf of the user, you MUST adhere to the
following safety tiers based on the action requested:
1. **Tier R: Read-Only**
* **Description:** Commands that only read state or query logs.
* **Example commands:**
* `gcloud logging read`
* `gcloud logging buckets list`
* **Rule:** No confirmation needed. You may execute these commands
immediately to gather information.
2. **Tier M: Mutation (Non-Billing)**
* **Description:** Configuration modifications or free metadata creations
that do not incur direct storage or billing costs and do not affect
resource security/access policies.
* **Example commands:**
* `gcloud logging views create`
* `gcloud logging views update`
* `gcloud logging scopes create`
* `gcloud logging buckets create`
* **Rule:** No confirmation needed. You may execute these commands
immediately to apply configurations.
3. **Tier B: Billing and Security-Sensitive Mutations (High-Risk)**
* **Description:** Operations that create billing-inducing resources or
integrations, or modify security and IAM access control policies
(presenting a risk of privilege escalation).
* **Example commands:**
* `gcloud logging metrics create`
* `gcloud logging links create`
* `gcloud projects add-iam-policy-binding`
* **Rule:** **Interactive confirmation required.** These commands create
resources that incur billing costs or alter security access. You MUST
present the exact, literal command and receive user confirmation before
executing. NEVER execute in the same turn as asking.
4. **Tier D: Causes irreversible data loss**
* **Description:** Actions that permanently discard or delete logs, for
example sink exclusions.
* **Example commands:**
* `gcloud logging buckets delete`
* `gcloud logging sinks update --add-exclusion`
* **Rule:** **Explicit typed confirmation required.** These commands
discard or delete logs immediately and irreversibly, or they may result
in log data not being stored. You MUST ask for explicit typed
confirmation, for example, "Yes, discard logs", and halt execution until
the user replies.
## Getting Started
If the `gcloud` executable is missing, refer to the
[Google Cloud CLI Installation Guide](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt)
to install it.
## Creating Log Buckets (Compliance and Analytics) (Tier M)
To create a regional log bucket with a specific retention policy for regulatory
compliance, and with Observability Analytics enabled:
> [!WARNING] **Mandatory Observability Analytics Downgrade Warning:** Whenever
> providing guidance, writing a guide, or drafting commands on Cloud Logging
> cost optimization or exclusions, you **must** explicitly include the following
> warning in your final text response and any generated guides: "After a log
> bucket has been upgraded to use Observability Analytics, it **cannot be
> downgraded** to remove the analytics capability."
```bash
gcloud logging buckets create {bucket_id} \
--project={project_id} \
--location={region} \
--retention-days={retention_days} \
--enable-analytics
```
* `{bucket_id}`: for example, `my-custom-bucket`
* `{region}`: for example, `us-central1`. You must use a regional log bucket
to also use Observability Analytics.
* `{retention_days}`: for example, `365`
A log bucket incurs no storage or ingestion charges until logs are routed to it
with a log sink.
### Verify the Log Bucket (Tier R)
Check the log bucket's configuration to verify its compliance:
```bash
gcloud logging buckets describe {bucket_id} \
--location={region} \
--project={project_id}
```
### Route logs to the Log Bucket (Tier B)
> [!IMPORTANT] **Billing Action (Tier B):** Routing log entries to a bucket
> incurs ongoing charges based on the volume of data stored. You MUST get
> interactive user confirmation before running this command.
Log entries are stored in the log bucket only if a log sink filter matches the
entries and targets that bucket.
To route log entries to the log bucket:
```bash
gcloud logging sinks create {sink_id} \
projects/{project_id}/locations/{region}/buckets/{bucket_id} \
--log-filter='{filter_expression}' \
--project={project_id}
```
--------------------------------------------------------------------------------
## Logs-Based Metrics
Logs-based metrics count the number of log entries that match a filter, allowing
you to track error rates and set up alerting policies.
### 1. Create a logs-based counter metric (Tier B)
> [!IMPORTANT] **Billing Action (Tier B):** Creating logs-based metrics incurs
> ongoing charges based on the volume of data points reported. You MUST get
> interactive user confirmation before running this command.
To count the occurrences of a specific log pattern, for example, "OutOfMemory"
errors:
```bash
gcloud logging metrics create {metric_name} \
--log-filter='{filter_expression}' \
--description='{description}' \
--project={project_id}
```
* `{metric_name}`: for example, `oom_error_count`
* `{filter_expression}`: for example, `textPayload:"OutOfMemory"`
* `{description}`: for example, "Count of log entries about OOMs"
Refer to
[REST Resource: projects.metric](https://docs.cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics.md.txt#LogMetric)
for restrictions on the metric fields.
### 2. Verify the logs-based metric (Tier R)
To verify that the metric exists and inspect its configuration, use the
`describe` command:
```bash
gcloud logging metrics describe {metric_name} \
--project={project_id}
```
--------------------------------------------------------------------------------
## Restricting Access to Sensitive Logs (Security)
Anyone with `roles/logging.viewer` on that project can see logs in a project's
`_Default` log bucket via `_Default` log view. To restrict visibility of the
logs:
> [!IMPORTANT] **Ambiguity Handling (Guidance for Agents):** If the user asks to
> "exclude", "hide", or "remove" sensitive logs without explicitly specifying
> whether they want to stop storing them, you **MUST** default to **excluding
> them from the default view (Step 1)**. This is a safe, non-destructive Tier M
> action. Only configure a storage exclusion (under the "Discarding Sensitive
> Logs from Storage" section) if the user explicitly uses destructive terms like
> *"stop storing"*, *"permanently discard"*, or *"sink exclusion"*.
### 1. Exclude sensitive logs from default view (Tier M)
To explicitly exclude sensitive logs from general access, update the filter for
the `_Default` log view:
```bash
gcloud logging views update _Default \
--bucket=_Default \
--location=global \
--project={project_id} \
--log-filter='NOT LOG_ID("cloudaudit.googleapis.com/data_access") AND NOT LOG_ID("externalaudit.googleapis.com/data_access") AND NOT LOG_ID("{sensitive_log_id}")'
```
### 2. Create a log view (Tier M)
Create a new log view that includes the sensitive logs in the project's
`_Default` log bucket. For example, a "security-logs-view" with access to the
`{sensitive_log_id}`
```bash
gcloud logging views create security-logs-view \
--bucket=_Default \
--location=global \
--project={project_id} \
--log-filter='LOG_ID("{sensitive_log_id}")' \
--description="Sensitive logs"
```
### 3. Grant access to log view using IAM conditions (Tier B)
> [!IMPORTANT] **Security Action (Tier B):** Granting IAM permissions changes
> access control policy and must be explicitly confirmed by the user before
> execution.
To restrict access to log view use IAM. When granting the Logs Viewer Accessor
role, always attach an IAM condition that restricts the grant to a specific log
view. For example, to grant `{security_group_email}` access ONLY to the
`security-logs-view` in the `_Default` bucket:
```bash
gcloud projects add-iam-policy-binding {project_id} \
--member='group:{security_group_email}' \
--role='roles/logging.viewAccessor' \
--condition="expression=resource.name=='projects/{project_id}/locations/global/buckets/_Default/views/security-logs-view',title=Restricted to Specific Log View,description=Only allows access to the specified log view"
```
Replace `{location}` with the location of the log bucket, for example `global`
or a regional location like `us-central1`.
### 4. Verify Sensitive Log Restrictions (Tier R)
To verify that your Log View for sensitive logs is configured correctly:
```bash
gcloud logging views describe {view_id} \
--bucket={bucket_id} \
--location={region} \
--project={project_id}
```
Ensure that the `filter` block contains the appropriate restriction expression.
--------------------------------------------------------------------------------
## Discarding Sensitive Logs from Storage (Tier D)
If your organization's compliance policies prohibit storing sensitive logs at
all, you can configure an exclusion to discard them before they are written to
disk.
> [!CAUTION] **Destructive Action (Tier D):** Excluding logs from all log sinks
> deletes the log entries immediately and irreversibly.
>
> **Safety Rule:** You MUST ask the user for explicit typed confirmation, for
> example, "I confirm I want to exclude `{sensitive_log_id}` logs from storage",
> before running this command. **Same-Turn Restriction:** Do NOT execute the
> `gcloud logging sinks update` command in the same turn as asking for
> confirmation. Stop tool execution immediately and wait for the user to reply.
**Exclude sensitive logs from storage using sink exclusions**
```bash
gcloud logging sinks update _Default \
--project={project_id} \
--add-exclusion=name=exclude-sensitive,filter='LOG_ID("{sensitive_log_id}")'
```
--------------------------------------------------------------------------------
## Cost Optimization (Reducing Logging Costs)
Cloud Logging costs are based on the volume of data ingested and stored. You can
reduce costs by excluding high-volume, low-value logs or by sampling them. Each
log sink that routes logs to a distinct log bucket contributes to cost and is a
candidate for optimization.
> [!CAUTION] **Destructive Actions (Tier D):** Exclusions in this section may
> immediately halt storage of log entries.
>
> **Safety Rule:** You MUST ask for explicit typed confirmation (for example, "I
> confirm I want to exclude load balancer logs") before executing exclusions or
> sampling updates.
### Exclude all high-volume logs (Tier D)
To completely stop ingesting a specific type of log into a log bucket, add an
exclusion to the log sinks that route logs into that bucket.
```bash
gcloud logging sinks update {sink_id} \
--project={project_id} \
--add-exclusion=name={exclusion_name},filter={exclusion_filter}
```
* `{sink_id}`: for example '_Default'
* `{exclusion_name}`: for example 'exclude-lb-logs'
* `{exclusion_filter}`: for example 'resource.type="http_load_balancer"'
### Sample high-volume logs (Tier D)
If you need some logs for analysis but want to reduce volume, use the `sample()`
function in the exclusion filter.
> [!IMPORTANT] The `sample(field, fraction)` function matches a `fraction` of
> logs. When used in an **exclusion filter**, the matched logs are
> **discarded**. If you exclude 90% of log entries, then only 10% are retained.
> To exclude 90%, use `sample(insertId, 0.9)` in the exclusion filter.
To exclude 90% of `DEBUG` severity logs:
```bash
gcloud logging sinks update _Default \
--project={project_id} \
--add-exclusion=name=sample-debug-logs,filter='severity=DEBUG AND sample(insertId, 0.9)'
```
### Verify Log Exclusions and Cost Optimization (Tier R)
To verify that log exclusions are correct, list the details of the sink and
check the `exclusions` to ensure your filter is present. For example, for the
`_Default` sink:
```bash
gcloud logging sinks describe _Default --project={project_id}
```
--------------------------------------------------------------------------------
## References and Supporting Links
* [Google Cloud Logging - Counter Metrics](https://docs.cloud.google.com/logging/docs/logs-based-metrics/counter-metrics.md.txt)
* [Google Cloud Logging - Custom Log Views](https://docs.cloud.google.com/logging/docs/logs-views.md.txt)
* [Google Cloud Logging - Exclusions](https://docs.cloud.google.com/logging/docs/routing/overview.md.txt)
Проверка и особенности
Автоматическая проверка источника и файлов
Автоматически сверены публичный репозиторий, лицензия, YAML-заголовок SKILL.md, состав папки и Git-хеш каждого файла. Исполняемые файлы и срабатывания статических правил исключены из этой партии. Ручной аудит всех инструкций и проверка работы не проводились; эта проверка не гарантирует безопасность. Команда закреплена на проверенном коммите.
Интерес к репозиторию оцениваем по звёздам и форкам GitHub. Это показатели всего репозитория, а не числа установок отдельного скилла.
Есть ссылки на внешние инструкции или инструменты: их содержимое и доступность могут изменяться отдельно от скилла.
- Проверка состава
- 16.09.2026
- Проверенная версия
569cb1d55ac3- Файлы с кодом
- Не указаны в данных проверки
- Изменения на GitHub
- Нужна повторная проверкаПоследняя проверка: 11.10.2026
Репозиторий и лицензия
Это показатели всего репозитория, а не установки скилла. Снимок требует обновления.
- Последняя активность GitHub
- 09.10.2026
- Лицензия
- Apache-2.0
- Добавлен в каталог
- 16.09.2026
Полный текст лицензии
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
Ещё в этой категории
Все в категорииОбсуждение
ПравилаПользовались этим скиллом? Делитесь опытом без регистрации. Все комментарии проверяет модератор.
