Skip to content

Commit

Permalink
fix(mongodb.go): improve error handling for MongoDB connection and in…
Browse files Browse the repository at this point in the history
…sertion

feat(mongodb.go): add logging for successful MongoDB connection and trace insertion
  • Loading branch information
HyunSu1768 committed Sep 11, 2024
1 parent acdcbf8 commit 6578eff
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions internal/repository/mongodb.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package repository

import (
"context"
"fmt"
"log"
"otel-trace-reciever/internal/models"

"go.mongodb.org/mongo-driver/mongo"
Expand All @@ -16,9 +18,16 @@ type MongoRepository struct {
func NewMongoRepository(uri string) (*MongoRepository, error) {
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(uri))
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to connect to MongoDB: %v", err)
}

err = client.Ping(context.Background(), nil)
if err != nil {
return nil, fmt.Errorf("failed to ping MongoDB: %v", err)
}

log.Println("Successfully connected to MongoDB")

return &MongoRepository{
client: client,
traceCollection: client.Database("tracing").Collection("traces"),
Expand All @@ -35,6 +44,15 @@ func (r *MongoRepository) SaveTraces(ctx context.Context, traces []*models.Trace
documents[i] = trace
}

_, err := r.traceCollection.InsertMany(ctx, documents)
return err
result, err := r.traceCollection.InsertMany(ctx, documents)
if err != nil {
return fmt.Errorf("failed to insert traces: %v", err)
}

log.Printf("Successfully inserted %d traces", len(result.InsertedIDs))
return nil
}

func (r *MongoRepository) Close(ctx context.Context) error {
return r.client.Disconnect(ctx)
}

0 comments on commit 6578eff

Please sign in to comment.