1
|
|
|
package cmd |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"context" |
5
|
|
|
"errors" |
6
|
|
|
"fmt" |
7
|
|
|
"log/slog" |
8
|
|
|
"os" |
9
|
|
|
|
10
|
|
|
"github.com/Permify/permify/pkg/telemetry" |
11
|
|
|
"github.com/Permify/permify/pkg/telemetry/logexporters" |
12
|
|
|
"github.com/Permify/sloggcp" |
13
|
|
|
"github.com/agoda-com/opentelemetry-go/otelslog" |
14
|
|
|
) |
15
|
|
|
|
16
|
|
|
// HandlerFactory - Create log handler according to given params |
17
|
|
|
func HandlerFactory(name string, endpoint string, insecure bool, urlpath string, headers map[string]string, protocol string, level slog.Leveler) (slog.Handler, error) { |
18
|
|
|
switch name { |
19
|
|
|
case "otlp", "otlp-http", "otlp-grpc": |
20
|
|
|
return NewOTLPHandler(endpoint, insecure, urlpath, headers, protocol, level.Level()) |
21
|
|
|
case "gcp": |
22
|
|
|
return NewGCPHandler(headers, level) |
23
|
|
|
default: |
24
|
|
|
return nil, fmt.Errorf("%s log handler is unsupported", name) |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
func NewOTLPHandler(endpoint string, insecure bool, urlPath string, headers map[string]string, protocol string, level slog.Leveler) (slog.Handler, error) { |
29
|
|
|
// Set up the OTLP exporter based on the protocol |
30
|
|
|
exporter, err := logexporters.ExporterFactory("otlp", endpoint, insecure, urlPath, headers, protocol) |
31
|
|
|
if err != nil { |
32
|
|
|
return nil, errors.New("failed to create OTLP exporter") |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
// Initialize the OpenTelemetry handler with the exporter |
36
|
|
|
lp := telemetry.NewLog(exporter) |
37
|
|
|
otelHandler := otelslog.NewOtelHandler(lp, &otelslog.HandlerOptions{ |
38
|
|
|
Level: level, |
39
|
|
|
}) |
40
|
|
|
|
41
|
|
|
// Shut down the exporter when needed |
42
|
|
|
return otelHandler, nil |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
func NewGCPHandler(headers map[string]string, level slog.Leveler) (slog.Handler, error) { |
46
|
|
|
// Retrieve Google Cloud credentials from headers |
47
|
|
|
creds := headers["google-application-credentials"] |
48
|
|
|
projectId := headers["google-cloud-project"] |
49
|
|
|
|
50
|
|
|
if projectId == "" { |
51
|
|
|
return nil, errors.New("missing GOOGLE_CLOUD_PROJECT in headers") |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
// Set credentials for Google Cloud access |
55
|
|
|
if creds != "" { |
56
|
|
|
os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", creds) |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
// Initialize GCP-specific log handler |
60
|
|
|
logName := "permify" |
61
|
|
|
gcpHandler := sloggcp.NewGoogleCloudSlogHandler(context.Background(), projectId, logName, &slog.HandlerOptions{ |
62
|
|
|
Level: level, |
63
|
|
|
}) |
64
|
|
|
return gcpHandler, nil |
65
|
|
|
} |
66
|
|
|
|