我正在创建一个日志接收器,它将接收另一个go程序的日志输出,进行一些过滤,然后直接POST到GCP日志。收到的日志记录是纯JSON条目。如果可以的话,我宁愿避免使用JSON marshall。仅仅将JSON作为JSON有效载荷添加到日志条目中并不能获得级别-->严重性或时间戳。我可以强制馈送Severity,但我对时间戳的尝试失败了。然而,最好的情况是有一个JSON字符串和一个很小的配置,上面写着在级别中查找Severity并使用时间戳字段。以下是我的最小示例:
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"time"
"cloud.google.com/go/logging"
)
func main() {
ctx := context.Background()
projectID := "redacted1"
client, err := logging.NewClient(ctx, projectID)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
logName := "redacted2"
logger := client.Logger(logName)
// JSON string
text := "{"decision_id":"21986d12-e3b2-47f3-b3c7-9a8d77bd048d","input":{"networks":[{"id":"net1","public":false},{"id":"net2","public":false},{"id":"net3","public":true},{"id":"net4","public":true}],"ports":[{"id":"p1","network":"net1"},{"id":"p2","network":"net3"},{"id":"p3","network":"net2"}],"servers":[{"id":"app","ports":["p1","p2","p3"],"protocols":["https","ssh"]},{"id":"db","ports":["p3"],"protocols":["mysql"]},{"id":"cache","ports":["p3"],"protocols":["memcache"]},{"id":"ci","ports":["p1","p2"],"protocols":["http"]},{"id":"busybox","ports":["p1"],"protocols":["telnet"]}]},"labels":{"id":"d29ba0a9-75d4-4d74-9d03-7bf0399a47c3","version":"0.23.2"},"level":"info","metrics":{"counter_server_query_cache_hit":0,"timer_rego_input_parse_ns":554348,"timer_rego_query_compile_ns":484825,"timer_rego_query_eval_ns":1002441,"timer_rego_query_parse_ns":46624,"timer_server_handler_ns":2290410},"msg":"Decision Log","path":"example/violation","requested_by":"127.0.0.1:44934","result":["ci","busybox"],"time":"2021-01-04T08:44:24-06:00","timestamp":"2021-01-04T14:44:24.215618442Z","type":"openpolicyagent.org/decision_logs"}"
sev := logging.Info
tim, err := time.Parse(time.RFC3339Nano, "2021-01-04T14:44:24.215618442Z")
if err != nil {
log.Fatalf("Failed to parse time: %v", err)
}
entry := logging.Entry{Payload: json.RawMessage([]byte(text)), Severity: sev,
Timestamp: tim}
err = logger.LogSync(ctx, entry)
if err != nil {
log.Fatalf("Failed to flush client: %v", err)
}
err = client.Close()
if err != nil {
log.Fatalf("Failed to close client: %v", err)
}
}
怎么样:
sev := logging.Info
if strings.Contains(""level":"info"", text) {
sev = logging.Info
} else if strings.Contains(""level":"debug"", text) {
sev = logging.Debug
}
但你可能最终想要运行
tokens := strings.Split(text, ":")
先在文本上搜索一次,然后搜索数组?不管怎样,你对它进行切片,你想要来自该字符串的数据,但你不想对其进行解组