Add synchronous logger for telemetry

This commit is contained in:
Shreyas Goenka 2025-03-05 14:54:30 +01:00
parent 3a3076d9ea
commit f6592d9bbd
No known key found for this signature in database
GPG Key ID: 92A07DF49CCB0622
2 changed files with 75 additions and 0 deletions

25
libs/telemetry/context.go Normal file
View File

@ -0,0 +1,25 @@
package telemetry
import (
"context"
"errors"
)
// Private type to store the telemetry logger in the context
type telemetryLogger int
// Key to store the telemetry logger in the context
var telemetryLoggerKey telemetryLogger
func WithNewLogger(ctx context.Context) context.Context {
return context.WithValue(ctx, telemetryLoggerKey, &logger{})
}
func fromContext(ctx context.Context) *logger {
v := ctx.Value(telemetryLoggerKey)
if v == nil {
panic(errors.New("telemetry logger not found in the context"))
}
return v.(*logger)
}

50
libs/telemetry/logger.go Normal file
View File

@ -0,0 +1,50 @@
package telemetry
import (
"context"
"github.com/databricks/cli/libs/telemetry/protos"
"github.com/google/uuid"
)
func Log(ctx context.Context, event protos.DatabricksCliLog) {
fromContext(ctx).log(event)
}
func GetLogs(ctx context.Context) []protos.FrontendLog {
return fromContext(ctx).getLogs()
}
func HasLogs(ctx context.Context) bool {
return len(fromContext(ctx).getLogs()) > 0
}
func SetExecutionContext(ctx context.Context, ec protos.ExecutionContext) {
fromContext(ctx).setExecutionContext(ec)
}
type logger struct {
logs []protos.FrontendLog
}
func (l *logger) log(event protos.DatabricksCliLog) {
if l.logs == nil {
l.logs = make([]protos.FrontendLog, 0)
}
l.logs = append(l.logs, protos.FrontendLog{
FrontendLogEventID: uuid.New().String(),
Entry: protos.FrontendLogEntry{
DatabricksCliLog: event,
},
})
}
func (l *logger) getLogs() []protos.FrontendLog {
return l.logs
}
func (l *logger) setExecutionContext(ec protos.ExecutionContext) {
for i := range l.logs {
l.logs[i].Entry.DatabricksCliLog.ExecutionContext = &ec
}
}