func main() {
	if len(os.Args) == 2 {
		usage("Missing command.")
	}
	if len(os.Args) != 3 {
		usage("")
	}

	projID := os.Args[1]
	command := os.Args[2]

	// [START setup]
	ctx := context.Background()
	client, err := logging.NewClient(ctx, projID)
	if err != nil {
		log.Fatalf("Failed to create logging client: %v", err)
	}

	adminClient, err := logadmin.NewClient(ctx, projID)
	if err != nil {
		log.Fatalf("Failed to create logadmin client: %v", err)
	}

	client.OnError = func(err error) {
		// Print an error to the local log.
		// For example, if Flush() failed.
		log.Printf("client.OnError: %v", err)
	}
	// [END setup]

	switch command {
	case "write":
		log.Print("Writing some log entries.")
		writeEntry(client)
		structuredWrite(client)

	case "read":
		log.Print("Fetching and printing log entries.")
		entries, err := getEntries(adminClient, projID)
		if err != nil {
			log.Fatalf("Could not get entries: %v", err)
		}
		log.Printf("Found %d entries.", len(entries))
		for _, entry := range entries {
			fmt.Printf("Entry: %6s @%s: %v\n",
				entry.Severity,
				entry.Timestamp.Format(time.RFC3339),
				entry.Payload)
		}

	case "delete":
		log.Print("Deleting log.")
		if err := deleteLog(adminClient); err != nil {
			log.Fatalf("Could not delete log: %v", err)
		}

	default:
		usage("Unknown command.")
	}
}
func TestSimplelog(t *testing.T) {
	tc := testutil.SystemTest(t)
	ctx := context.Background()

	client, err := logging.NewClient(ctx, tc.ProjectID)
	if err != nil {
		t.Fatalf("logging.NewClient: %v", err)
	}
	adminClient, err := logadmin.NewClient(ctx, tc.ProjectID)
	if err != nil {
		t.Fatalf("logadmin.NewClient: %v", err)
	}
	defer func() {
		if err := client.Close(); err != nil {
			t.Errorf("Close: %v", err)
		}
	}()

	defer func() {
		testutil.Retry(t, 10, time.Second, func(r *testutil.R) {
			if err := deleteLog(adminClient); err != nil {
				r.Errorf("deleteLog: %v", err)
			}
		})
	}()

	client.OnError = func(err error) {
		t.Errorf("OnError: %v", err)
	}

	writeEntry(client)
	structuredWrite(client)

	testutil.Retry(t, 10, time.Second, func(r *testutil.R) {
		entries, err := getEntries(adminClient, tc.ProjectID)
		if err != nil {
			r.Errorf("getEntries: %v", err)
			return
		}

		if got, want := len(entries), 2; got != want {
			r.Errorf("len(entries) = %d; want %d", got, want)
			return
		}

		wantContain := map[string]*logging.Entry{
			"Anything":                            entries[0],
			"The payload can be any type!":        entries[0],
			"infolog is a standard Go log.Logger": entries[1],
		}

		for want, entry := range wantContain {
			msg := fmt.Sprintf("%s", entry.Payload)
			if !strings.Contains(msg, want) {
				r.Errorf("want %q to contain %q", msg, want)
			}
		}
	})
}
func ExampleClient_Entries() {
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	it := client.Entries(ctx, logadmin.Filter(`logName = "projects/my-project/logs/my-log"`))
	_ = it // TODO: iterate using Next or iterator.Pager.
}
func ExampleClient_Sinks() {
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	it := client.Sinks(ctx)
	_ = it // TODO: iterate using Next or iterator.Pager.
}
Exemple #5
0
func ExampleClient_DeleteMetric() {
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	if err := client.DeleteMetric(ctx, "severe-errors"); err != nil {
		// TODO: Handle error.
	}
}
Exemple #6
0
func ExampleClient_DeleteLog() {
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	err = client.DeleteLog(ctx, "my-log")
	if err != nil {
		// TODO: Handle error.
	}
}
func ExampleFilter_timestamp() {
	// This example demonstrates how to list the last 24 hours of log entries.
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	oneDayAgo := time.Now().Add(-24 * time.Hour)
	t := oneDayAgo.Format(time.RFC3339) // Logging API wants timestamps in RFC 3339 format.
	it := client.Entries(ctx, logadmin.Filter(fmt.Sprintf(`timestamp > "%s"`, t)))
	_ = it // TODO: iterate using Next or iterator.Pager.
}
Exemple #8
0
func ExampleClient_Metric() {
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	m, err := client.Metric(ctx, "severe-errors")
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(m)
}
Exemple #9
0
func ExampleClient_Sink() {
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	s, err := client.Sink(ctx, "severe-errors-to-gcs")
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(s)
}
Exemple #10
0
func ExampleNewClient() {
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	// Use client to manage logs, metrics and sinks.
	// Close the client when finished.
	if err := client.Close(); err != nil {
		// TODO: Handle error.
	}
}
Exemple #11
0
func ExampleClient_UpdateMetric() {
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	err = client.UpdateMetric(ctx, &logadmin.Metric{
		ID:          "severe-errors",
		Description: "entries at high severities",
		Filter:      "severity > ERROR",
	})
	if err != nil {
		// TODO: Handle error.
	}
}
Exemple #12
0
func ExampleClient_UpdateSink() {
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	sink, err := client.UpdateSink(ctx, &logadmin.Sink{
		ID:          "severe-errors-to-gcs",
		Destination: "storage.googleapis.com/my-other-bucket",
		Filter:      "severity >= ERROR",
	})
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(sink)
}
func main() {
	if len(os.Args) == 2 {
		usage("Missing command.")
	}
	if len(os.Args) != 3 {
		usage("")
	}

	projID := os.Args[1]
	command := os.Args[2]

	// [START create_logging_client]
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, projID)
	if err != nil {
		log.Fatalf("logadmin.NewClient: %v", err)
	}
	// [END create_logging_client]

	switch command {
	case "list":
		log.Print("Listing log sinks.")
		sinks, err := listSinks(client)
		if err != nil {
			log.Fatalf("Could not list log sinks: %v", err)
		}
		for _, sink := range sinks {
			fmt.Printf("Sink: %v\n", sink)
		}
	case "create":
		if err := createSink(client); err != nil {
			log.Fatalf("Could not create sink: %v", err)
		}
	case "update":
		if err := updateSink(client); err != nil {
			log.Fatalf("Could not update sink: %v", err)
		}
	case "delete":
		if err := deleteSink(client); err != nil {
			log.Fatalf("Could not delete sink: %v", err)
		}
	default:
		usage("Unknown command.")
	}
}
func ExampleSinkIterator_Next() {
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	it := client.Sinks(ctx)
	for {
		sink, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		fmt.Println(sink)
	}
}
func ExampleResourceDescriptorIterator_Next() {
	ctx := context.Background()
	client, err := logadmin.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	it := client.ResourceDescriptors(ctx)
	for {
		rdesc, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		fmt.Println(rdesc)
	}
}
func ExampleClient_Entries_pagination() {
	// This example demonstrates how to iterate through items a page at a time
	// even if each successive page is fetched by a different process. It is a
	// complete web server that displays pages of log entries. To run it as a
	// standalone program, rename both the package and this function to "main".
	ctx := context.Background()
	flag.Parse()
	if *projectID == "" {
		log.Fatal("-project-id missing")
	}
	var err error
	client, err = logadmin.NewClient(ctx, *projectID)
	if err != nil {
		log.Fatalf("creating logging client: %v", err)
	}

	http.HandleFunc("/entries", handleEntries)
	log.Print("listening on 8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}
Exemple #17
0
func TestMain(m *testing.M) {
	flag.Parse() // needed for testing.Short()
	ctx := context.Background()
	testProjectID = testutil.ProjID()
	errorc = make(chan error, 100)
	if testProjectID == "" || testing.Short() {
		integrationTest = false
		if testProjectID != "" {
			log.Print("Integration tests skipped in short mode (using fake instead)")
		}
		testProjectID = "PROJECT_ID"
		clean = func(e *logging.Entry) {
			// Remove the insert ID for consistency with the integration test.
			e.InsertID = ""
		}

		addr, err := ltesting.NewServer()
		if err != nil {
			log.Fatalf("creating fake server: %v", err)
		}
		logging.SetNow(testNow)

		newClients = func(ctx context.Context, projectID string) (*logging.Client, *logadmin.Client) {
			conn, err := grpc.Dial(addr, grpc.WithInsecure())
			if err != nil {
				log.Fatalf("dialing %q: %v", addr, err)
			}
			c, err := logging.NewClient(ctx, projectID, option.WithGRPCConn(conn))
			if err != nil {
				log.Fatalf("creating client for fake at %q: %v", addr, err)
			}
			ac, err := logadmin.NewClient(ctx, projectID, option.WithGRPCConn(conn))
			if err != nil {
				log.Fatalf("creating client for fake at %q: %v", addr, err)
			}
			return c, ac
		}

	} else {
		integrationTest = true
		clean = func(e *logging.Entry) {
			// We cannot compare timestamps, so set them to the test time.
			// Also, remove the insert ID added by the service.
			e.Timestamp = testNow().UTC()
			e.InsertID = ""
		}
		ts := testutil.TokenSource(ctx, logging.AdminScope)
		if ts == nil {
			log.Fatal("The project key must be set. See CONTRIBUTING.md for details")
		}
		log.Printf("running integration tests with project %s", testProjectID)
		newClients = func(ctx context.Context, projectID string) (*logging.Client, *logadmin.Client) {
			c, err := logging.NewClient(ctx, projectID, option.WithTokenSource(ts))
			if err != nil {
				log.Fatalf("creating prod client: %v", err)
			}
			ac, err := logadmin.NewClient(ctx, projectID, option.WithTokenSource(ts))
			if err != nil {
				log.Fatalf("creating prod client: %v", err)
			}
			return c, ac
		}

	}
	client, aclient = newClients(ctx, testProjectID)
	client.OnError = func(e error) { errorc <- e }
	initLogs(ctx)
	testFilter = fmt.Sprintf(`logName = "projects/%s/logs/%s"`, testProjectID,
		strings.Replace(testLogID, "/", "%2F", -1))
	exit := m.Run()
	client.Close()
	os.Exit(exit)
}