Skip to content

Commit ac99e02

Browse files
authored
chore: simplify tracing (#55)
* chore: simplify tracing * chore: cleanup
1 parent 8c96891 commit ac99e02

File tree

11 files changed

+227
-170
lines changed

11 files changed

+227
-170
lines changed

src/cmd/calendar.go

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@ import (
88

99
"github.com/SpechtLabs/CalendarAPI/pkg/api"
1010
pb "github.com/SpechtLabs/CalendarAPI/pkg/protos"
11+
"github.com/spechtlabs/go-otel-utils/otelzap"
1112
"github.com/spf13/cobra"
13+
"go.uber.org/zap"
14+
"google.golang.org/grpc"
1215
"gopkg.in/yaml.v3"
1316
)
1417

@@ -20,22 +23,23 @@ var clearCalendarCmd = &cobra.Command{
2023
Long: "Clear the cache of the server and force it to fetch the latest info from the iCal",
2124
Args: cobra.ExactArgs(0),
2225
Run: func(cmd *cobra.Command, args []string) {
23-
undo, zapLog, otelZap := initTelemetry()
24-
defer zapLog.Sync()
25-
defer undo()
26-
2726
addr := fmt.Sprintf("%s:%d", hostname, grpcPort)
2827

29-
conn, client := api.NewGrpcApiClient(otelZap, addr)
30-
defer conn.Close()
28+
conn, client := api.NewGrpcApiClient(addr)
29+
defer func(conn *grpc.ClientConn) {
30+
err := conn.Close()
31+
if err != nil {
32+
otelzap.L().Sugar().Errorw("failed to close gRPC connection", zap.Error(err))
33+
}
34+
}(conn)
3135

3236
// Contact the server
3337
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
3438
defer cancel()
3539

3640
_, err := client.RefreshCalendar(ctx, &pb.CalendarRequest{CalendarName: "all"})
3741
if err != nil {
38-
zapLog.Fatal(fmt.Sprintf("Failed to talk to gRPC API (%s) %v", addr, err))
42+
otelzap.L().Fatal(fmt.Sprintf("Failed to talk to gRPC API (%s) %v", addr, err))
3943
}
4044

4145
fmt.Print("Cleared calendar cache\n")
@@ -47,41 +51,42 @@ var getCalendarCmd = &cobra.Command{
4751
Example: "meetingepd get calendar",
4852
Args: cobra.MaximumNArgs(1),
4953
Run: func(cmd *cobra.Command, args []string) {
50-
undo, zapLog, otelZap := initTelemetry()
51-
defer zapLog.Sync()
52-
defer undo()
53-
5454
calendarName := "all"
5555
if len(args) == 1 {
5656
calendarName = args[0]
5757
}
5858

5959
addr := fmt.Sprintf("%s:%d", hostname, grpcPort)
6060

61-
conn, client := api.NewGrpcApiClient(otelZap, addr)
62-
defer conn.Close()
61+
conn, client := api.NewGrpcApiClient(addr)
62+
defer func(conn *grpc.ClientConn) {
63+
err := conn.Close()
64+
if err != nil {
65+
otelzap.L().Sugar().Errorw("failed to close gRPC connection", zap.Error(err))
66+
}
67+
}(conn)
6368

6469
// Contact the server
6570
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
6671
defer cancel()
6772

6873
calendar, err := client.GetCalendar(ctx, &pb.CalendarRequest{CalendarName: calendarName})
6974
if err != nil {
70-
zapLog.Fatal(fmt.Sprintf("Failed to talk to gRPC API (%s) %v", addr, err))
75+
otelzap.L().Fatal(fmt.Sprintf("Failed to talk to gRPC API (%s) %v", addr, err))
7176
}
7277

7378
switch outFormat {
7479
case "json":
7580
json, err := json.Marshal(calendar)
7681
if err != nil {
77-
zapLog.Sugar().Error(err)
82+
otelzap.L().Sugar().Error("failed to parse calendar config", zap.Error(err))
7883
}
7984
fmt.Println(string(json))
8085

8186
case "yaml":
8287
yaml, err := yaml.Marshal(calendar)
8388
if err != nil {
84-
zapLog.Sugar().Error(err)
89+
otelzap.L().Sugar().Error("failed to parse calendar config", zap.Error(err))
8590
}
8691
fmt.Println(string(yaml))
8792

src/cmd/customStatus.go

Lines changed: 30 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ import (
77

88
"github.com/SpechtLabs/CalendarAPI/pkg/api"
99
pb "github.com/SpechtLabs/CalendarAPI/pkg/protos"
10+
"github.com/spechtlabs/go-otel-utils/otelzap"
1011
"github.com/spf13/cobra"
12+
"go.uber.org/zap"
13+
"google.golang.org/grpc"
1114
)
1215

1316
var (
@@ -22,22 +25,23 @@ var getCustomStatusCmd = &cobra.Command{
2225
Example: "meetingepd get status",
2326
Args: cobra.ExactArgs(0),
2427
Run: func(cmd *cobra.Command, args []string) {
25-
undo, zapLog, otelZap := initTelemetry()
26-
defer zapLog.Sync()
27-
defer undo()
28-
2928
addr := fmt.Sprintf("%s:%d", hostname, grpcPort)
3029

31-
conn, client := api.NewGrpcApiClient(otelZap, addr)
32-
defer conn.Close()
30+
conn, client := api.NewGrpcApiClient(addr)
31+
defer func(conn *grpc.ClientConn) {
32+
err := conn.Close()
33+
if err != nil {
34+
otelzap.L().Sugar().Errorw("failed to close gRPC connection", zap.Error(err))
35+
}
36+
}(conn)
3337

3438
// Contact the server
3539
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
3640
defer cancel()
3741

3842
customStatus, err := client.GetCustomStatus(ctx, &pb.GetCustomStatusRequest{CalendarName: calendar})
3943
if err != nil {
40-
zapLog.Fatal(fmt.Sprintf("Failed to talk to gRPC API (%s) %v", addr, err))
44+
otelzap.L().Fatal(fmt.Sprintf("Failed to talk to gRPC API (%s) %v", addr, err))
4145
}
4246

4347
fmt.Print("Custom Status:")
@@ -57,14 +61,15 @@ var setCustomStatusCmd = &cobra.Command{
5761
Example: "meetingepd set status",
5862
Args: cobra.ExactArgs(1),
5963
Run: func(cmd *cobra.Command, args []string) {
60-
undo, zapLog, otelZap := initTelemetry()
61-
defer zapLog.Sync()
62-
defer undo()
63-
6464
addr := fmt.Sprintf("%s:%d", hostname, grpcPort)
6565

66-
conn, client := api.NewGrpcApiClient(otelZap, addr)
67-
defer conn.Close()
66+
conn, client := api.NewGrpcApiClient(addr)
67+
defer func(conn *grpc.ClientConn) {
68+
err := conn.Close()
69+
if err != nil {
70+
otelzap.L().Sugar().Errorw("failed to close gRPC connection", zap.Error(err))
71+
}
72+
}(conn)
6873

6974
// Contact the server
7075
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
@@ -80,7 +85,7 @@ var setCustomStatusCmd = &cobra.Command{
8085
},
8186
})
8287
if err != nil {
83-
zapLog.Fatal(fmt.Sprintf("Failed to talk to gRPC API (%s) %v", addr, err))
88+
otelzap.L().Fatal(fmt.Sprintf("Failed to talk to gRPC API (%s) %v", addr, err))
8489
}
8590

8691
fmt.Print("Set Custom Status:")
@@ -100,22 +105,23 @@ var clearCustomStatusCmd = &cobra.Command{
100105
Example: "meetingepd clear status",
101106
Args: cobra.ExactArgs(0),
102107
Run: func(cmd *cobra.Command, args []string) {
103-
undo, zapLog, otelZap := initTelemetry()
104-
defer zapLog.Sync()
105-
defer undo()
106-
107108
addr := fmt.Sprintf("%s:%d", hostname, grpcPort)
108109

109-
conn, client := api.NewGrpcApiClient(otelZap, addr)
110-
defer conn.Close()
110+
conn, client := api.NewGrpcApiClient(addr)
111+
defer func(conn *grpc.ClientConn) {
112+
err := conn.Close()
113+
if err != nil {
114+
otelzap.L().Sugar().Errorw("failed to close gRPC connection", zap.Error(err))
115+
}
116+
}(conn)
111117

112118
// Contact the server
113119
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
114120
defer cancel()
115121

116122
_, err := client.ClearCustomStatus(ctx, &pb.ClearCustomStatusRequest{CalendarName: calendar})
117123
if err != nil {
118-
zapLog.Fatal(fmt.Sprintf("Failed to talk to gRPC API (%s) %v", addr, err))
124+
otelzap.L().Fatal(fmt.Sprintf("Failed to talk to gRPC API (%s) %v", addr, err))
119125
}
120126

121127
fmt.Print("Cleared Custom Status\n")
@@ -128,13 +134,13 @@ func init() {
128134
setCustomStatusCmd.Flags().Int32Var(&iconSize, "icon_size", 196, "Icon size to display in the custom status")
129135

130136
setCustomStatusCmd.Flags().StringVarP(&calendar, "calendar", "q", "", "Name of the calendar to set the custom status for")
131-
setCustomStatusCmd.MarkFlagRequired("calendar")
137+
_ = setCustomStatusCmd.MarkFlagRequired("calendar")
132138

133139
getCustomStatusCmd.Flags().StringVarP(&calendar, "calendar", "q", "", "Name of the calendar to set the custom status for")
134-
getCustomStatusCmd.MarkFlagRequired("calendar")
140+
_ = getCustomStatusCmd.MarkFlagRequired("calendar")
135141

136142
clearCustomStatusCmd.Flags().StringVarP(&calendar, "calendar", "q", "", "Name of the calendar to set the custom status for")
137-
clearCustomStatusCmd.MarkFlagRequired("calendar")
143+
_ = clearCustomStatusCmd.MarkFlagRequired("calendar")
138144

139145
setCmd.AddCommand(setCustomStatusCmd)
140146
getCmd.AddCommand(getCustomStatusCmd)

src/cmd/root.go

Lines changed: 1 addition & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,8 @@ import (
55
"os"
66
"time"
77

8-
"github.com/gin-gonic/gin"
98
"github.com/spf13/cobra"
109
"github.com/spf13/viper"
11-
"github.com/uptrace/opentelemetry-go-extra/otelzap"
12-
"go.uber.org/zap"
1310
)
1411

1512
var (
@@ -28,39 +25,11 @@ var (
2825
hostname string
2926
grpcPort int
3027
restPort int
31-
defaultCalendarRefresh time.Duration = 30 * time.Minute
28+
defaultCalendarRefresh = 30 * time.Minute
3229
configFileName string
3330
debug bool
3431
)
3532

36-
func initTelemetry() (func(), *zap.Logger, *otelzap.Logger) {
37-
var err error
38-
39-
// Initialize Logging
40-
var zapLog *zap.Logger
41-
if debug {
42-
zapLog, err = zap.NewDevelopment()
43-
gin.SetMode(gin.DebugMode)
44-
} else {
45-
zapLog, err = zap.NewProduction()
46-
gin.SetMode(gin.ReleaseMode)
47-
}
48-
49-
if err != nil {
50-
panic(fmt.Errorf("failed to initialize logger: %w", err))
51-
}
52-
53-
otelZap := otelzap.New(zapLog,
54-
otelzap.WithCaller(true),
55-
otelzap.WithErrorStatusLevel(zap.ErrorLevel),
56-
otelzap.WithStackTrace(false),
57-
)
58-
59-
undo := otelzap.ReplaceGlobals(otelZap)
60-
61-
return undo, zapLog, otelZap
62-
}
63-
6433
func init() {
6534
cobra.OnInitialize(initConfig)
6635

src/cmd/serve.go

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,16 @@ import (
1111
"github.com/SpechtLabs/CalendarAPI/pkg/api"
1212
"github.com/SpechtLabs/CalendarAPI/pkg/client"
1313
"github.com/fsnotify/fsnotify"
14+
"github.com/spechtlabs/go-otel-utils/otelzap"
1415
"github.com/spf13/cobra"
1516
"github.com/spf13/viper"
16-
"github.com/uptrace/opentelemetry-go-extra/otelzap"
17-
"go.uber.org/zap"
1817
)
1918

20-
func initCalendarRefresh(zapLog *otelzap.Logger, iCalClient *client.ICalClient) chan struct{} {
19+
func initCalendarRefresh(iCalClient *client.ICalClient) chan struct{} {
2120
refreshConfig := viper.GetString("server.refresh")
2221
refresh, err := time.ParseDuration(refreshConfig)
2322
if err != nil {
24-
zapLog.Sugar().Errorf("Failed to parse '%s' as time.Duration: %v. Failing back to default refresh duration (%s)",
23+
otelzap.L().Sugar().Errorf("Failed to parse '%s' as time.Duration: %v. Failing back to default refresh duration (%s)",
2524
refreshConfig, err.Error(),
2625
defaultCalendarRefresh,
2726
)
@@ -48,24 +47,19 @@ func initCalendarRefresh(zapLog *otelzap.Logger, iCalClient *client.ICalClient)
4847
return quitRefreshTicker
4948
}
5049

51-
func viperConfigChange(undo func(), zapLog *zap.Logger, otelZap *otelzap.Logger, iCalClient *client.ICalClient, quitRefreshTicker *chan struct{}) {
50+
func viperConfigChange(iCalClient *client.ICalClient, quitRefreshTicker *chan struct{}) {
5251
viper.OnConfigChange(func(e fsnotify.Event) {
5352
otelzap.L().Sugar().Infow("Config file change detected. Reloading.", "filename", e.Name)
5453
iCalClient.FetchEvents(context.Background())
5554

56-
// refresh logger
57-
zapLog.Sync()
58-
undo()
59-
undo, zapLog, otelZap = initTelemetry()
60-
6155
// Refresh calendar watch timer
6256
close(*quitRefreshTicker)
63-
*quitRefreshTicker = initCalendarRefresh(otelZap, iCalClient)
57+
*quitRefreshTicker = initCalendarRefresh(iCalClient)
6458

6559
if hostname != viper.GetString("server.host") ||
6660
grpcPort != viper.GetInt("server.grpcPort") ||
6761
restPort != viper.GetInt("server.httpPort") {
68-
zapLog.Sugar().Errorw("Unable to change host or port at runtime!",
62+
otelzap.L().Sugar().Errorw("Unable to change host or port at runtime!",
6963
"new_host", viper.GetString("server.host"),
7064
"old_host", hostname,
7165
"new_grpcPort", viper.GetInt("server.grpcPort"),
@@ -83,35 +77,31 @@ var serveCmd = &cobra.Command{
8377
Example: "meetingepd version",
8478
Args: cobra.ExactArgs(0),
8579
Run: func(cmd *cobra.Command, args []string) {
86-
undo, zapLog, otelZap := initTelemetry()
87-
defer zapLog.Sync()
88-
defer undo()
89-
9080
if debug {
9181
file, err := os.ReadFile(viper.GetViper().ConfigFileUsed())
9282
if err != nil {
9383
panic(fmt.Errorf("fatal error reading config file: %w", err))
9484
}
95-
zapLog.Sugar().With("config_file", string(file)).Debug("Config file used")
85+
otelzap.L().Sugar().With("config_file", string(file)).Debug("Config file used")
9686
}
9787

98-
iCalClient := client.NewICalClient(otelZap)
88+
iCalClient := client.NewICalClient()
9989

100-
quitRefreshTicker := initCalendarRefresh(otelZap, iCalClient)
101-
viperConfigChange(undo, zapLog, otelZap, iCalClient, &quitRefreshTicker)
90+
quitRefreshTicker := initCalendarRefresh(iCalClient)
91+
viperConfigChange(iCalClient, &quitRefreshTicker)
10292
viper.WatchConfig()
10393

10494
// Serve Rest-API
10595
go func() {
106-
restApiServer := api.NewRestApiServer(otelZap, iCalClient)
96+
restApiServer := api.NewRestApiServer(iCalClient)
10797
if err := restApiServer.ListenAndServe(); err != nil {
10898
panic(err.Error())
10999
}
110100
}()
111101

112102
// Serve gRPC-API
113103
go func() {
114-
gRpcApiServer := api.NewGrpcApiServer(otelZap, iCalClient)
104+
gRpcApiServer := api.NewGrpcApiServer(iCalClient)
115105
if err := gRpcApiServer.Serve(); err != nil {
116106
panic(err.Error())
117107
}

0 commit comments

Comments
 (0)