-
Notifications
You must be signed in to change notification settings - Fork 2
/
simplelog.go
176 lines (152 loc) · 4.31 KB
/
simplelog.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Sample simplelog writes some entries, lists them, then deletes the log.
package main
import (
"fmt"
"log"
"os"
"time"
// [START imports]
"context"
"cloud.google.com/go/logging"
"cloud.google.com/go/logging/logadmin"
"google.golang.org/api/iterator"
// [END imports]
)
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 writeEntry(client *logging.Client) {
// [START logging_write_log_entry]
println("Start write entry")
const name = "log-example"
logger := client.Logger(name)
defer logger.Flush() // Ensure the entry is written.
infolog := logger.StandardLogger(logging.Info)
infolog.Printf("infolog is a standard Go log.Logger with INFO severity.")
// [END logging_write_log_entry]
}
func structuredWrite(client *logging.Client) {
println("Start structured write entry")
// [START write_structured_log_entry]
const name = "log-example"
logger := client.Logger(name)
defer logger.Flush() // Ensure the entry is written.
logger.Log(logging.Entry{
// Log anything that can be marshaled to JSON.
Payload: struct{ Anything string }{
Anything: "The payload can be any type!",
},
Severity: logging.Debug,
})
// [END write_structured_log_entry]
}
func deleteLog(adminClient *logadmin.Client) error {
ctx := context.Background()
// [START logging_delete_log]
const name = "log-example"
if err := adminClient.DeleteLog(ctx, name); err != nil {
return err
}
// [END logging_delete_log]
return nil
}
func getEntries(adminClient *logadmin.Client, projID string) ([]*logging.Entry, error) {
println("Start getting entries")
ctx := context.Background()
// [START logging_list_log_entries]
var entries []*logging.Entry
const name = "log-example"
iter := adminClient.Entries(ctx,
// Only get entries from the log-example log.
logadmin.Filter(fmt.Sprintf(`logName = "projects/%s/logs/%s"`, projID, name)),
// Get most recent entries first.
logadmin.NewestFirst(),
)
println("Fetching the most recent 20 entries")
// Fetch the most recent 5 entries.
for len(entries) < 5 {
println("Fetching the most recent entries")
entry, err := iter.Next()
if err == iterator.Done {
println("Done fetching")
return entries, nil
}
if err != nil {
println("Found error")
return nil, err
}
println(entry)
entries = append(entries, entry)
}
return entries, nil
// [END logging_list_log_entries]
}
func usage(msg string) {
if msg != "" {
fmt.Fprintln(os.Stderr, msg)
}
fmt.Fprintln(os.Stderr, "usage: simplelog <project-id> [write|read|delete]")
os.Exit(2)
}