Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Nós fornecemos um pacote de geração de registros compatível com a biblioteca padrão. A
biblioteca do Cloud Logging para Go expõe uma camada de nível superior para trabalhar com
o Cloud Logging.
O agente do Cloud Logging não precisa ser instalado para usar a
biblioteca do Cloud Logging para Go em uma instância de VM do Compute Engine.
Antes de começar
Sign in to your Google Cloud account. If you're new to
Google Cloud,
create an account to evaluate how our products perform in
real-world scenarios. New customers also get $300 in free credits to
run, test, and deploy workloads.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
// Sample stdlogging writes log.Logger logs to the Cloud Logging.packagemainimport("context""log""cloud.google.com/go/logging")funcmain(){ctx:=context.Background()// Sets your Google Cloud Platform project ID.projectID:="YOUR_PROJECT_ID"// Creates a client.client,err:=logging.NewClient(ctx,projectID)iferr!=nil{log.Fatalf("Failed to create client: %v",err)}deferclient.Close()// Sets the name of the log to write to.logName:="my-log"logger:=client.Logger(logName).StandardLogger(logging.Info)// Logs "hello world", log entry is visible at// Cloud Logs.logger.Println("hello world")}
Para mais informações sobre a instalação, consulte a
documentação da
biblioteca do Cloud Logging para Go. Também é possível informar problemas usando o
Issue Tracker.
Gravar registros com a biblioteca de cliente do Cloud Logging
Para que um aplicativo grave registros usando a biblioteca do Cloud Logging para Go, a
conta de serviço do recurso subjacente precisa ter o papel do gravador de registros (roles/logging.logWriter) do IAM.
A maioria dos ambientes do Google Cloud configura automaticamente a conta de serviço padrão para ter esse papel.
App Engine
O Cloud Logging é ativado automaticamente para o App Engine, e a
conta de serviço padrão do aplicativo tem
as permissões do IAM por padrão para gravar entradas de registro.
O GKE concede automaticamente à conta de serviço padrão o papel do IAM de Gravador de registros (roles/logging.logWriter).
Se você usar a
Federação de identidade da carga de trabalho para GKE
com essa conta de serviço padrão para permitir que as cargas de trabalho acessem APIs
específicas doGoogle Cloud , nenhuma configuração adicional será necessária.
No entanto, se você usar a Federação de Identidade da Carga de Trabalho para GKE com uma conta de serviço personalizada do IAM, verifique se ela tem a função de gravador de registros (roles/logging.logWriter).
Se necessário, também é possível usar o seguinte comando para adicionar o escopo de acesso logging.write
ao criar o cluster:
Ao usar instâncias de VM do Compute Engine, adicione o escopo de acesso cloud-platform a cada instância. Ao criar uma nova instância pelo console doGoogle Cloud , faça isso na seção Identidade e acesso à API do painel Criar instância. Use a conta de serviço padrão do Compute Engine ou outra de sua escolha e selecione Permitir acesso completo a todas as APIs do Cloud na seção Identidade e acesso à API. Seja qual for a conta de serviço selecionada, verifique se ela recebeu o papel de gravador de registros na seção IAM e administrador doGoogle Cloud console.
Execute localmente e em outro lugar
Para usar a biblioteca do Cloud Logging para Go fora do Google Cloud, incluindo a execução da biblioteca na sua estação de trabalho, nos computadores do seu data center ou nas instâncias de VM de outro provedor de nuvem, é necessário configurar o Application Default Credentials (ADC) no seu ambiente local para autenticar a biblioteca do Cloud Logging para Go.
Se você usar a barra de pesquisa para encontrar essa página, selecione o resultado com o subtítulo Logging.
No Explorador de registros, é preciso especificar um ou mais recursos, mas a escolha deles
pode não ser óbvia. Veja a seguir algumas dicas para ajudar você a começar:
Se você estiver implantando seu aplicativo no App Engine ou usando as bibliotecas específicas dele, defina seu recurso como Aplicativo do GAE.
Se você estiver implantando seu aplicativo no Compute Engine, defina o recurso como Instância de VM do GCE.
Se você estiver implantando seu aplicativo no Google Kubernetes Engine, a configuração
de geração de registros do cluster determinará o tipo de recurso das entradas
de registro. Para uma discussão detalhada sobre as soluções do Legacy Google Cloud Observability e do Kubernetes Monitoring do Google Cloud Observability e como essas opções afetam o tipo de recurso, consulte Como migrar para o Kubernetes Monitoring do Google Cloud Observability.
Se o aplicativo estiver usando a API Cloud Logging diretamente,
o recurso dependerá da API e da configuração. Por exemplo,
no seu aplicativo, é possível especificar um recurso ou usar um recurso padrão.
Se você não vir registros no Explorador de registros, alterne para o modo de consulta
avançada e use uma consulta vazia para ver todas as entradas de registro.
Se quiser alternar para o modo de consulta avançada, clique no menu (▾)
na parte superior do Explorador de registros e
selecione Converter para filtro avançado.
Limpe o conteúdo que aparece na caixa de filtro.
Clique em Enviar filtro.
É possível examinar as entradas individuais para identificar seus recursos.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-11 UTC."],[],[],null,["# Setting Up Cloud Logging for Go\n\nWe provide a standard library-compatible logging package. The\nCloud Logging library for Go exposes a higher-level layer for working with\nCloud Logging.\n\nThe Cloud Logging agent does not have to be installed to use the\nCloud Logging library for Go on a Compute Engine VM instance.\n\nBefore you begin\n----------------\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Logging API.\n\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=logging.googleapis.com)\n\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Logging API.\n\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=logging.googleapis.com)\n\n\n### Installing the package\n\n```\ngo get cloud.google.com/go/logging\n```\n\n### Using the Go logger\n\n\n // Sample stdlogging writes log.Logger logs to the Cloud Logging.\n package main\n\n import (\n \t\"context\"\n \t\"log\"\n\n \t\"cloud.google.com/go/logging\"\n )\n\n func main() {\n \tctx := context.Background()\n\n \t// Sets your Google Cloud Platform project ID.\n \tprojectID := \"YOUR_PROJECT_ID\"\n\n \t// Creates a client.\n \tclient, err := logging.NewClient(ctx, projectID)\n \tif err != nil {\n \t\tlog.Fatalf(\"Failed to create client: %v\", err)\n \t}\n \tdefer client.Close()\n\n \t// Sets the name of the log to write to.\n \tlogName := \"my-log\"\n\n \tlogger := client.Logger(logName).https://cloud.google.com/go/docs/reference/cloud.google.com/go/logging/latest/index.html#cloud_google_com_go_logging_Logger_StandardLogger(logging.https://cloud.google.com/go/docs/reference/cloud.google.com/go/logging/latest/index.html#cloud_google_com_go_logging_Default_Debug_Info_Notice_Warning_Error_Critical_Alert_Emergency)\n\n \t// Logs \"hello world\", log entry is visible at\n \t// Cloud Logs.\n \tlogger.Println(\"hello world\")\n }\n\n\u003cbr /\u003e\n\nFor more information on installation, see the\n[documentation](/go/logging) for the\nCloud Logging library for Go. You can also report issues using the\n[issue tracker](https://github.com/GoogleCloudPlatform/google-cloud-go/issues).\n\nWrite logs with the Cloud Logging client library\n------------------------------------------------\n\nFor information on using the Cloud Logging client library for\nGo directly, see [Cloud Logging Client Libraries](/logging/docs/reference/libraries).\n\nRun on Google Cloud\n-------------------\n\nFor an application to write logs by using the Cloud Logging library for Go, the\nservice account for the underlying resource must have the\n[Logs Writer (`roles/logging.logWriter`)](/logging/docs/access-control#permissions_and_roles) [IAM](/iam/docs/understanding-roles) role.\nMost Google Cloud environments automatically configure the default\nservice account to have this role.\n\n### App Engine\n\nCloud Logging is automatically enabled for App Engine, and your app's\n[default service account](/appengine/docs/standard/go/service-account) has\nthe IAM permissions by default to write log entries.\n\nFor more information, see [Writing and viewing\nlogs](/appengine/docs/standard/go/writing-application-logs).\n\n### Google Kubernetes Engine (GKE)\n\n[GKE](/kubernetes-engine/docs) automatically grants the default service account\nthe [Logs Writer (`roles/logging.logWriter`)](/logging/docs/access-control#permissions_and_roles) IAM role.\nIf you use\n[Workload Identity Federation for GKE](/kubernetes-engine/docs/concepts/workload-identity)\nwith this default service account to let workloads access specific\nGoogle Cloud APIs, then no additional configuration is required.\nHowever, if you use Workload Identity Federation for GKE with a\ncustom IAM service account, then ensure that the custom service\naccount has the role of Logs Writer (`roles/logging.logWriter`).\n\nIf needed, you can also use the following command to add the `logging.write`\naccess scope when creating the cluster: \n\n gcloud container clusters create example-cluster-name \\\n --scopes https://www.googleapis.com/auth/logging.write\n\n### Compute Engine\n\n| **Note:** To use the Cloud Logging library for Go on a **Compute Engine** VM instance, you do not need to install the Cloud Logging agent.\n\nWhen using [Compute Engine](/compute/docs) VM instances, add the `cloud-platform`\naccess scope to each instance. When creating a new instance through the\nGoogle Cloud console, you can do this in the **Identity and API access** section\nof the **Create Instance** panel. Use the Compute Engine default service\naccount or another service account of your choice, and select\n**Allow full access to all Cloud APIs** in the **Identity and API access**\nsection. Whichever service\naccount you select, ensure that it has been granted the\n[Logs Writer role](/logging/docs/access-control#permissions_and_roles) in the **IAM \\& Admin** section of the\nGoogle Cloud console.\n\nRun locally and elsewhere\n-------------------------\n\nTo use the Cloud Logging library for Go outside of Google Cloud,\nincluding running the library on your own workstation, on your data center's\ncomputers, or on the VM instances of another cloud provider, you must\nset up Application Default Credentials (ADC) in your local environment to\nauthenticate to the Cloud Logging library for Go.\n\nFor more information, see\n[Set up ADC for on-premises or another cloud provider](/docs/authentication/set-up-adc-on-premises).\n\nView the logs\n-------------\n\nIn the Google Cloud console, go to the **Logs Explorer** page:\n\n[Go to **Logs Explorer**](https://console.cloud.google.com/logs/query)\n\n\u003cbr /\u003e\n\nIf you use the search bar to find this page, then select the result whose subheading is\n**Logging**.\n\nIn the Logs Explorer, you must specify one or more resources, but the resource\nselection might not be obvious. Here are some tips to help you get\nstarted:\n\n- If you are deploying your application to App Engine or using the\n App Engine-specific libraries, set your resource to\n **GAE Application**.\n\n- If you are deploying your application on Compute Engine, set the resource\n to **GCE VM Instance**.\n\n- If you are deploying your application on Google Kubernetes Engine, your\n cluster's logging configuration determines the resource type of the log\n entries. For a detailed\n discussion on the Legacy Google Cloud Observability and the Google Cloud Observability\n Kubernetes Monitoring solutions, and how those options affect the\n resource type, see\n [Migrating to Google Cloud Observability Kubernetes Monitoring](/monitoring/kubernetes-engine/migration#stackdriver-options).\n\n- If your application is using the Cloud Logging API directly,\n the resource is dependent on the API and your configuration. For example,\n in your application, you can specify a resource or use a default resource.\n\n- If you don't see any logs in the Logs Explorer, to see all log entries,\n switch to the advanced query mode and use an empty query.\n\n 1. To switch to the advanced query mode, click **menu** (▾) at the top of the Logs Explorer and then select **Convert to advanced filter**.\n 2. Clear the content that appears in the filter box.\n 3. Click **Submit Filter**.\n\n You can examine the individual entries to identify your resources.\n\nFor additional information, see [Using the Logs Explorer](/logging/docs/view/logs-explorer-interface)."]]