...

Source file src/cloud.google.com/go/logging/doc.go

Documentation: cloud.google.com/go/logging

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

View as plain text