go-http-server-with-otel/main.go

74 lines
1.7 KiB
Go
Raw Normal View History

2025-01-03 22:13:15 +00:00
// This template contains a simple
// app with OTEL bootstrap that will create an
// HTTP server configured by environment that exports
// spans and metrics to an OTEL collector if configured
// to do so. Will also stand up a prometheus metrics
// endpoint.
2025-01-04 02:09:40 +00:00
//
// Configuration and logger stored in context
2025-01-03 22:13:15 +00:00
package main
import (
"context"
"os"
"os/signal"
2025-01-04 02:49:59 +00:00
"time"
2025-01-03 22:13:15 +00:00
2025-01-04 02:09:40 +00:00
"github.com/rs/zerolog"
2025-01-04 02:49:59 +00:00
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
2025-01-03 22:13:15 +00:00
"golang.org/x/sys/unix"
"gitea.libretechconsulting.com/rmcguire/go-http-server-with-otel/pkg/config"
2025-01-04 02:09:40 +00:00
"gitea.libretechconsulting.com/rmcguire/go-http-server-with-otel/pkg/logging"
2025-01-04 02:49:59 +00:00
"gitea.libretechconsulting.com/rmcguire/go-http-server-with-otel/pkg/observability"
2025-01-03 22:13:15 +00:00
)
func main() {
ctx, cncl := signal.NotifyContext(context.Background(), os.Interrupt, unix.SIGTERM)
defer cncl()
2025-01-04 02:09:40 +00:00
// Set up app config and logging
ctx, err := config.LoadConfig(ctx)
2025-01-03 22:13:15 +00:00
if err != nil {
panic(err)
}
2025-01-04 02:09:40 +00:00
cfg := config.MustFromCtx(ctx)
ctx = logging.MustInitLogging(ctx)
l := zerolog.Ctx(ctx)
2025-01-04 02:49:59 +00:00
// Set up OTEL
opts := make([]observability.Option, 0)
if cfg.Logging.Level == "trace" {
opts = append(opts, observability.EnableStdoutExporter)
}
shutdown := observability.Init(ctx, opts...)
defer func() {
shutdownCtx, cncl := context.WithTimeout(context.Background(), 30*time.Second)
defer cncl()
shutdown(shutdownCtx)
}()
// Begin Server init
tracer := otel.Tracer(cfg.Name)
_, initSpan := tracer.Start(ctx, "init")
// TODO: HTTP Server
// App Ready
2025-01-04 02:09:40 +00:00
l.Trace().Any("config", *cfg).Send()
l.Info().
Str("name", cfg.Name).
Str("version", cfg.Version).
Str("logLevel", cfg.Logging.Level).
Msg("app initialized")
2025-01-03 22:13:15 +00:00
2025-01-04 02:49:59 +00:00
initSpan.SetStatus(codes.Ok, "")
initSpan.End()
2025-01-04 02:09:40 +00:00
<-ctx.Done()
2025-01-03 22:13:15 +00:00
}
func init() {}