doc.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. // Copyright 2016 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /*
  15. Package logging contains a Cloud Logging client suitable for writing logs.
  16. For reading logs, and working with sinks, metrics and monitored resources,
  17. see package cloud.google.com/go/logging/logadmin.
  18. This client uses Logging API v2.
  19. See https://cloud.google.com/logging/docs/api/v2/ for an introduction to the API.
  20. # Creating a Client
  21. Use a Client to interact with the Cloud Logging API.
  22. // Create a Client
  23. ctx := context.Background()
  24. client, err := logging.NewClient(ctx, "my-project")
  25. if err != nil {
  26. // TODO: Handle error.
  27. }
  28. # Basic Usage
  29. For most use cases, you'll want to add log entries to a buffer to be periodically
  30. flushed (automatically and asynchronously) to the Cloud Logging service.
  31. // Initialize a logger
  32. lg := client.Logger("my-log")
  33. // Add entry to log buffer
  34. lg.Log(logging.Entry{Payload: "something happened!"})
  35. # Closing your Client
  36. You should call Client.Close before your program exits to flush any buffered log entries to the Cloud Logging service.
  37. // Close the client when finished.
  38. err = client.Close()
  39. if err != nil {
  40. // TODO: Handle error.
  41. }
  42. # Synchronous Logging
  43. For critical errors, you may want to send your log entries immediately.
  44. LogSync is slow and will block until the log entry has been sent, so it is
  45. not recommended for normal use.
  46. err = lg.LogSync(ctx, logging.Entry{Payload: "ALERT! Something critical happened!"})
  47. if err != nil {
  48. // TODO: Handle error.
  49. }
  50. # Redirecting log ingestion
  51. For cases when runtime environment supports out-of-process log ingestion,
  52. like logging agent, you can opt-in to write log entries to io.Writer instead of
  53. ingesting them to Cloud Logging service. Usually, you will use os.Stdout or os.Stderr as
  54. writers because Google Cloud logging agents are configured to capture logs from standard output.
  55. The entries will be Jsonified and wrote as one line strings following the structured logging format.
  56. See https://cloud.google.com/logging/docs/structured-logging#special-payload-fields for the format description.
  57. To instruct Logger to redirect log entries add RedirectAsJSON() LoggerOption`s.
  58. // Create a logger to print structured logs formatted as a single line Json to stdout
  59. loggger := client.Logger("test-log", RedirectAsJSON(os.Stdout))
  60. # Payloads
  61. An entry payload can be a string, as in the examples above. It can also be any value
  62. that can be marshaled to a JSON object, like a map[string]interface{} or a struct:
  63. type MyEntry struct {
  64. Name string
  65. Count int
  66. }
  67. lg.Log(logging.Entry{Payload: MyEntry{Name: "Bob", Count: 3}})
  68. If you have a []byte of JSON, wrap it in json.RawMessage:
  69. j := []byte(`{"Name": "Bob", "Count": 3}`)
  70. lg.Log(logging.Entry{Payload: json.RawMessage(j)})
  71. If you have proto.Message and want to send it as a protobuf payload, marshal it to anypb.Any:
  72. // import
  73. func logMessage (m proto.Message) {
  74. var payload anypb.Any
  75. err := anypb.MarshalFrom(&payload, m)
  76. if err != nil {
  77. lg.Log(logging.Entry{Payload: payload})
  78. }
  79. }
  80. # The Standard Logger
  81. You may want use a standard log.Logger in your program.
  82. // stdlg is an instance of *log.Logger.
  83. stdlg := lg.StandardLogger(logging.Info)
  84. stdlg.Println("some info")
  85. # Log Levels
  86. An Entry may have one of a number of severity levels associated with it.
  87. logging.Entry{
  88. Payload: "something terrible happened!",
  89. Severity: logging.Critical,
  90. }
  91. # Viewing Logs
  92. You can view Cloud logs for projects at
  93. https://console.cloud.google.com/logs/viewer. Use the dropdown at the top left. When
  94. running from a Google Cloud Platform VM, select "GCE VM Instance". Otherwise, select
  95. "Google Project" and then the project ID. Logs for organizations, folders and billing
  96. accounts can be viewed on the command line with the "gcloud logging read" command.
  97. # Grouping Logs by Request
  98. To group all the log entries written during a single HTTP request, create two
  99. Loggers, a "parent" and a "child," with different log IDs. Both should be in the same
  100. project, and have the same MonitoredResource type and labels.
  101. - Parent entries must have HTTPRequest.Request (strictly speaking, only Method and URL are necessary),
  102. and HTTPRequest.Status populated.
  103. - A child entry's timestamp must be within the time interval covered by the parent request. (i.e., before
  104. the parent.Timestamp and after the parent.Timestamp - parent.HTTPRequest.Latency. This assumes the
  105. parent.Timestamp marks the end of the request.)
  106. - The trace field must be populated in all of the entries and match exactly.
  107. You should observe the child log entries grouped under the parent on the console. The
  108. parent entry will not inherit the severity of its children; you must update the
  109. parent severity yourself.
  110. */
  111. package logging // import "cloud.google.com/go/logging"