...

Source file src/cloud.google.com/go/logging/examples_test.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  package logging_test
    16  
    17  import (
    18  	"context"
    19  	"encoding/json"
    20  	"fmt"
    21  	"net/http"
    22  	"os"
    23  
    24  	"cloud.google.com/go/logging"
    25  	vkit "cloud.google.com/go/logging/apiv2"
    26  	logpb "cloud.google.com/go/logging/apiv2/loggingpb"
    27  	"go.opencensus.io/trace"
    28  )
    29  
    30  func ExampleNewClient() {
    31  	ctx := context.Background()
    32  	client, err := logging.NewClient(ctx, "my-project")
    33  	if err != nil {
    34  		// TODO: Handle error.
    35  	}
    36  	// Use client to manage logs, metrics and sinks.
    37  	// Close the client when finished.
    38  	if err := client.Close(); err != nil {
    39  		// TODO: Handle error.
    40  	}
    41  }
    42  
    43  func ExampleClient_Ping() {
    44  	ctx := context.Background()
    45  	client, err := logging.NewClient(ctx, "my-project")
    46  	if err != nil {
    47  		// TODO: Handle error.
    48  	}
    49  	if err := client.Ping(ctx); err != nil {
    50  		// TODO: Handle error.
    51  	}
    52  }
    53  
    54  // Although Logger.Flush and Client.Close both return errors, they don't tell you
    55  // whether the errors were frequent or significant. For most programs, it doesn't
    56  // matter if there were a few errors while writing logs, although if those few errors
    57  // indicated a bug in your program, you might want to know about them. The best way
    58  // to handle errors is by setting the OnError function. If it runs quickly, it will
    59  // see every error generated during logging.
    60  func ExampleNewClient_errorFunc() {
    61  	ctx := context.Background()
    62  	client, err := logging.NewClient(ctx, "my-project")
    63  	if err != nil {
    64  		// TODO: Handle error.
    65  	}
    66  	// Print all errors to stdout, and count them. Multiple calls to the OnError
    67  	// function never happen concurrently, so there is no need for locking nErrs,
    68  	// provided you don't read it until after the logging client is closed.
    69  	var nErrs int
    70  	client.OnError = func(e error) {
    71  		fmt.Fprintf(os.Stdout, "logging: %v", e)
    72  		nErrs++
    73  	}
    74  	// Use client to manage logs, metrics and sinks.
    75  	// Close the client when finished.
    76  	if err := client.Close(); err != nil {
    77  		// TODO: Handle error.
    78  	}
    79  	fmt.Printf("saw %d errors\n", nErrs)
    80  }
    81  
    82  func ExampleClient_Logger() {
    83  	ctx := context.Background()
    84  	client, err := logging.NewClient(ctx, "my-project")
    85  	if err != nil {
    86  		// TODO: Handle error.
    87  	}
    88  	lg := client.Logger("my-log")
    89  	_ = lg // TODO: use the Logger.
    90  }
    91  
    92  func ExampleHTTPRequest() {
    93  	ctx := context.Background()
    94  	client, err := logging.NewClient(ctx, "my-project")
    95  	if err != nil {
    96  		// TODO: Handle error.
    97  	}
    98  	lg := client.Logger("my-log")
    99  	httpEntry := logging.Entry{
   100  		Payload: "optional message",
   101  		HTTPRequest: &logging.HTTPRequest{
   102  			// TODO: pass in request
   103  			Request: &http.Request{},
   104  			// TODO: set the status code
   105  			Status: http.StatusOK,
   106  		},
   107  	}
   108  	lg.Log(httpEntry)
   109  }
   110  
   111  func ExampleToLogEntry() {
   112  	e := logging.Entry{
   113  		Payload: "Message",
   114  	}
   115  	le, err := logging.ToLogEntry(e, "my-project")
   116  	if err != nil {
   117  		// TODO: Handle error.
   118  	}
   119  	client, err := vkit.NewClient(context.Background())
   120  	if err != nil {
   121  		// TODO: Handle error.
   122  	}
   123  	_, err = client.WriteLogEntries(context.Background(), &logpb.WriteLogEntriesRequest{
   124  		Entries: []*logpb.LogEntry{le},
   125  		LogName: "stdout",
   126  	})
   127  	if err != nil {
   128  		// TODO: Handle error.
   129  	}
   130  }
   131  
   132  func ExampleLogger_LogSync() {
   133  	ctx := context.Background()
   134  	client, err := logging.NewClient(ctx, "my-project")
   135  	if err != nil {
   136  		// TODO: Handle error.
   137  	}
   138  	lg := client.Logger("my-log")
   139  	err = lg.LogSync(ctx, logging.Entry{Payload: "red alert"})
   140  	if err != nil {
   141  		// TODO: Handle error.
   142  	}
   143  }
   144  
   145  func ExampleLogger_Log() {
   146  	ctx := context.Background()
   147  	client, err := logging.NewClient(ctx, "my-project")
   148  	if err != nil {
   149  		// TODO: Handle error.
   150  	}
   151  	lg := client.Logger("my-log")
   152  	lg.Log(logging.Entry{Payload: "something happened"})
   153  }
   154  
   155  // An Entry payload can be anything that marshals to a
   156  // JSON object, like a struct.
   157  func ExampleLogger_Log_struct() {
   158  	type MyEntry struct {
   159  		Name  string
   160  		Count int
   161  	}
   162  
   163  	ctx := context.Background()
   164  	client, err := logging.NewClient(ctx, "my-project")
   165  	if err != nil {
   166  		// TODO: Handle error.
   167  	}
   168  	lg := client.Logger("my-log")
   169  	lg.Log(logging.Entry{Payload: MyEntry{Name: "Bob", Count: 3}})
   170  }
   171  
   172  // To log a JSON value, wrap it in json.RawMessage.
   173  func ExampleLogger_Log_json() {
   174  	ctx := context.Background()
   175  	client, err := logging.NewClient(ctx, "my-project")
   176  	if err != nil {
   177  		// TODO: Handle error.
   178  	}
   179  	lg := client.Logger("my-log")
   180  	j := []byte(`{"Name": "Bob", "Count": 3}`)
   181  	lg.Log(logging.Entry{Payload: json.RawMessage(j)})
   182  }
   183  
   184  func ExampleLogger_Flush() {
   185  	ctx := context.Background()
   186  	client, err := logging.NewClient(ctx, "my-project")
   187  	if err != nil {
   188  		// TODO: Handle error.
   189  	}
   190  	lg := client.Logger("my-log")
   191  	lg.Log(logging.Entry{Payload: "something happened"})
   192  	lg.Flush()
   193  }
   194  
   195  func ExampleLogger_StandardLogger() {
   196  	ctx := context.Background()
   197  	client, err := logging.NewClient(ctx, "my-project")
   198  	if err != nil {
   199  		// TODO: Handle error.
   200  	}
   201  	lg := client.Logger("my-log")
   202  	slg := lg.StandardLogger(logging.Info)
   203  	slg.Println("an informative message")
   204  }
   205  
   206  func ExampleLogger_StandardLoggerFromTemplate() {
   207  	ctx := context.Background()
   208  	client, err := logging.NewClient(ctx, "my-project")
   209  	if err != nil {
   210  		// TODO: Handle error.
   211  	}
   212  	lg := client.Logger("my-log")
   213  	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
   214  		slg := lg.StandardLoggerFromTemplate(&logging.Entry{
   215  			Severity:    logging.Info,
   216  			HTTPRequest: &logging.HTTPRequest{Request: r},
   217  		})
   218  		slg.Println("Before hello world")
   219  		fmt.Fprintf(w, "Hello world!\n")
   220  	})
   221  }
   222  
   223  func ExampleParseSeverity() {
   224  	sev := logging.ParseSeverity("ALERT")
   225  	fmt.Println(sev)
   226  	// Output: Alert
   227  }
   228  
   229  // This example shows how to create a Logger that disables OpenCensus tracing of the
   230  // WriteLogEntries RPC.
   231  func ExampleContextFunc() {
   232  	ctx := context.Background()
   233  	client, err := logging.NewClient(ctx, "my-project")
   234  	if err != nil {
   235  		// TODO: Handle error.
   236  	}
   237  	lg := client.Logger("logID", logging.ContextFunc(func() (context.Context, func()) {
   238  		ctx, span := trace.StartSpan(context.Background(), "this span will not be exported",
   239  			trace.WithSampler(trace.NeverSample()))
   240  		return ctx, span.End
   241  	}))
   242  	_ = lg // TODO: Use lg
   243  }
   244  

View as plain text