diff --git a/examples/using-migrations/main.go b/examples/using-migrations/main.go index f5fbaf10e..c8f0161b1 100644 --- a/examples/using-migrations/main.go +++ b/examples/using-migrations/main.go @@ -49,7 +49,7 @@ func GetHandler(c *gofr.Context) (interface{}, error) { err := c.SQL.QueryRowContext(c, queryGetEmployee, name). Scan(&emp.ID, &emp.Name, &emp.Gender, &emp.Phone, &emp.DOB) if err != nil { - return nil, errors.New(fmt.Sprintf("DB Error : %v", err)) + return nil, errors.New(fmt.Sprintf("DB Error: %v", err)) } return emp, nil @@ -66,8 +66,8 @@ func PostHandler(c *gofr.Context) (interface{}, error) { // Execute the INSERT query _, err := c.SQL.ExecContext(c, queryInsertEmployee, emp.ID, emp.Name, emp.Gender, emp.Phone, emp.DOB) if err != nil { - return Employee{}, errors.New(fmt.Sprintf("DB Error : %v", err)) + return Employee{}, errors.New(fmt.Sprintf("DB Error: %v", err)) } - return fmt.Sprintf("successfully posted entity : %v", emp.Name), nil + return fmt.Sprintf("successfully posted entity: %v", emp.Name), nil } diff --git a/go.mod b/go.mod index d4de9b7d4..760676a00 100644 --- a/go.mod +++ b/go.mod @@ -33,7 +33,7 @@ require ( go.uber.org/mock v0.4.0 golang.org/x/oauth2 v0.18.0 golang.org/x/term v0.18.0 - google.golang.org/api v0.170.0 + google.golang.org/api v0.171.0 google.golang.org/grpc v1.62.1 google.golang.org/protobuf v1.33.0 ) @@ -57,7 +57,7 @@ require ( github.com/google/go-cmp v0.6.0 // indirect github.com/google/s2a-go v0.1.7 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect - github.com/googleapis/gax-go/v2 v2.12.2 // indirect + github.com/googleapis/gax-go/v2 v2.12.3 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/klauspost/compress v1.16.6 // indirect github.com/openzipkin/zipkin-go v0.4.2 // indirect @@ -81,7 +81,7 @@ require ( golang.org/x/time v0.5.0 // indirect google.golang.org/appengine v1.6.8 // indirect google.golang.org/genproto v0.0.0-20240213162025-012b6fc9bca9 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20240304161311-37d4d3c04a78 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20240311132316-a219d84964c2 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20240311132316-a219d84964c2 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240314234333-6e1732d8331c // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 4d188de4e..3b4338fe0 100644 --- a/go.sum +++ b/go.sum @@ -103,8 +103,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs= github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= -github.com/googleapis/gax-go/v2 v2.12.2 h1:mhN09QQW1jEWeMF74zGR81R30z4VJzjZsfkUhuHF+DA= -github.com/googleapis/gax-go/v2 v2.12.2/go.mod h1:61M8vcyyXR2kqKFxKrfA22jaA8JGF7Dc8App1U3H6jc= +github.com/googleapis/gax-go/v2 v2.12.3 h1:5/zPPDvw8Q1SuXjrqrZslrqT7dL/uJT2CQii/cLCKqA= +github.com/googleapis/gax-go/v2 v2.12.3/go.mod h1:AKloxT6GtNbaLm8QTNSidHUVsHYcBHwWRvkNFJUQcS4= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= @@ -314,8 +314,8 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.170.0 h1:zMaruDePM88zxZBG+NG8+reALO2rfLhe/JShitLyT48= -google.golang.org/api v0.170.0/go.mod h1:/xql9M2btF85xac/VAm4PsLMTLVGUOpq4BE9R8jyNy8= +google.golang.org/api v0.171.0 h1:w174hnBPqut76FzW5Qaupt7zY8Kql6fiVjgys4f58sU= +google.golang.org/api v0.171.0/go.mod h1:Hnq5AHm4OTMt2BUVjael2CWZFD6vksJdWCWiUAmjC9o= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= @@ -326,10 +326,10 @@ google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfG google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20240213162025-012b6fc9bca9 h1:9+tzLLstTlPTRyJTh+ah5wIMsBW5c4tQwGTN3thOW9Y= google.golang.org/genproto v0.0.0-20240213162025-012b6fc9bca9/go.mod h1:mqHbVIp48Muh7Ywss/AD6I5kNVKZMmAa/QEW58Gxp2s= -google.golang.org/genproto/googleapis/api v0.0.0-20240304161311-37d4d3c04a78 h1:SzXBGiWM1LNVYLCRP3e0/Gsze804l4jGoJ5lYysEO5I= -google.golang.org/genproto/googleapis/api v0.0.0-20240304161311-37d4d3c04a78/go.mod h1:O1cOfN1Cy6QEYr7VxtjOyP5AdAuR0aJ/MYZaaof623Y= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240311132316-a219d84964c2 h1:9IZDv+/GcI6u+a4jRFRLxQs0RUCfavGfoOgEW6jpkI0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240311132316-a219d84964c2/go.mod h1:UCOku4NytXMJuLQE5VuqA5lX3PcHCBo8pxNyvkf4xBs= +google.golang.org/genproto/googleapis/api v0.0.0-20240311132316-a219d84964c2 h1:rIo7ocm2roD9DcFIX67Ym8icoGCKSARAiPljFhh5suQ= +google.golang.org/genproto/googleapis/api v0.0.0-20240311132316-a219d84964c2/go.mod h1:O1cOfN1Cy6QEYr7VxtjOyP5AdAuR0aJ/MYZaaof623Y= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240314234333-6e1732d8331c h1:lfpJ/2rWPa/kJgxyyXM8PrNnfCzcmxJ265mADgwmvLI= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240314234333-6e1732d8331c/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= diff --git a/pkg/gofr/container/health_test.go b/pkg/gofr/container/health_test.go index e55fdf68e..93fa8f790 100644 --- a/pkg/gofr/container/health_test.go +++ b/pkg/gofr/container/health_test.go @@ -19,7 +19,7 @@ import ( func TestContainer_Health(t *testing.T) { mockDB, mock, err := sqlmock.New() if err != nil { - t.Fatalf("could not initialize mock database err : %v", err) + t.Fatalf("could not initialize mock database err: %v", err) } srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/gofr/datasource/pubsub/google/google.go b/pkg/gofr/datasource/pubsub/google/google.go index 8b1e54366..2674c4321 100644 --- a/pkg/gofr/datasource/pubsub/google/google.go +++ b/pkg/gofr/datasource/pubsub/google/google.go @@ -35,7 +35,7 @@ type googleClient struct { func New(conf Config, logger pubsub.Logger, metrics Metrics) *googleClient { err := validateConfigs(&conf) if err != nil { - logger.Errorf("google pubsub could not be configured, err : %v", err) + logger.Errorf("google pubsub could not be configured, err: %v", err) return nil } @@ -47,6 +47,8 @@ func New(conf Config, logger pubsub.Logger, metrics Metrics) *googleClient { } } + logger.Debugf("intialized google pubsub client, projectID: %s", client.Project()) + return &googleClient{ Config: conf, client: client, @@ -158,7 +160,7 @@ func (g *googleClient) getSubscription(ctx context.Context, topic *gcPubSub.Topi // check if subscription already exists or not ok, err := subscription.Exists(context.Background()) if err != nil { - g.logger.Errorf("unable to check the existence of subscription, err : %v ", err.Error()) + g.logger.Errorf("unable to check the existence of subscription, err: %v ", err.Error()) return nil, err } diff --git a/pkg/gofr/datasource/pubsub/kafka/health.go b/pkg/gofr/datasource/pubsub/kafka/health.go index 32361b943..a065d570e 100644 --- a/pkg/gofr/datasource/pubsub/kafka/health.go +++ b/pkg/gofr/datasource/pubsub/kafka/health.go @@ -30,7 +30,7 @@ func (k *kafkaClient) getReaderStatsAsMap() []interface{} { for _, reader := range k.reader { var readerStat map[string]interface{} if err := convertStructToMap(reader.Stats(), &readerStat); err != nil { - k.logger.Errorf("Kafka Reader Stats processing failed: %v", err) + k.logger.Errorf("kafka Reader Stats processing failed: %v", err) continue // Log the error but continue processing other readers } @@ -44,7 +44,7 @@ func (k *kafkaClient) getWriterStatsAsMap() map[string]interface{} { writerStats := make(map[string]interface{}) if err := convertStructToMap(k.writer.Stats(), &writerStats); err != nil { - k.logger.Errorf("Kafka Writer Stats processing failed: %v", err) + k.logger.Errorf("kafka Writer Stats processing failed: %v", err) return nil } diff --git a/pkg/gofr/datasource/pubsub/kafka/kafka.go b/pkg/gofr/datasource/pubsub/kafka/kafka.go index b8e41a127..7c4885b64 100644 --- a/pkg/gofr/datasource/pubsub/kafka/kafka.go +++ b/pkg/gofr/datasource/pubsub/kafka/kafka.go @@ -43,14 +43,14 @@ type kafkaClient struct { func New(conf Config, logger pubsub.Logger, metrics Metrics) *kafkaClient { err := validateConfigs(conf) if err != nil { - logger.Errorf("could not initialize kafka, err : %v", err) + logger.Errorf("could not initialize kafka, err: %v", err) return nil } conn, err := kafka.Dial("tcp", conf.Broker) if err != nil { - logger.Errorf("Failed to connect to KAFKA at %v", conf.Broker) + logger.Errorf("failed to connect to KAFKA at %v", conf.Broker) } dialer := &kafka.Dialer{ @@ -65,6 +65,8 @@ func New(conf Config, logger pubsub.Logger, metrics Metrics) *kafkaClient { reader := make(map[string]Reader) + logger.Debugf("connected to Kafka, broker: %s", conf.Broker) + return &kafkaClient{ config: conf, dialer: dialer, diff --git a/pkg/gofr/datasource/pubsub/mqtt/mqtt.go b/pkg/gofr/datasource/pubsub/mqtt/mqtt.go index d44b297c6..9429eb982 100644 --- a/pkg/gofr/datasource/pubsub/mqtt/mqtt.go +++ b/pkg/gofr/datasource/pubsub/mqtt/mqtt.go @@ -99,7 +99,7 @@ func getDefaultClient(config *Config, logger Logger, metrics Metrics) *MQTT { msg := make(map[string]chan *pubsub.Message) - logger.Debugf("connected to MQTT, HostName : %v, Port : %v", config.Hostname, config.Port) + logger.Debugf("connected to MQTT, HostName: %v, Port: %v", config.Hostname, config.Port) logger.Debugf("using %v clientID for this MQTT session", clientID) return &MQTT{Client: client, config: config, logger: logger, msgChanMap: msg, mu: new(sync.RWMutex), metrics: metrics} @@ -194,7 +194,7 @@ func (m *MQTT) Publish(ctx context.Context, topic string, message []byte) error // Check for errors during publishing (More on error reporting // https://pkg.go.dev/github.com/eclipse/paho.mqtt.golang#readme-error-handling) if token.Wait() && token.Error() != nil { - m.logger.Errorf("error while publishing message, err : %v", token.Error()) + m.logger.Errorf("error while publishing message, err %v", token.Error()) return token.Error() } @@ -238,7 +238,7 @@ func (m *MQTT) CreateTopic(_ context.Context, topic string) error { token.Wait() if token.Error() != nil { - m.logger.Errorf("unable to create topic - %s, error : %v", topic, token.Error()) + m.logger.Errorf("unable to create topic - %s, error: %v", topic, token.Error()) return token.Error() } @@ -288,7 +288,7 @@ func (m *MQTT) Unsubscribe(topic string) error { token.Wait() if token.Error() != nil { - m.logger.Errorf("error while unsubscribing from topic %s, err : %v", topic, token.Error()) + m.logger.Errorf("error while unsubscribing from topic %s, err: %v", topic, token.Error()) return token.Error() } diff --git a/pkg/gofr/datasource/pubsub/mqtt/mqtt_test.go b/pkg/gofr/datasource/pubsub/mqtt/mqtt_test.go index 1bb15c55a..38919d406 100644 --- a/pkg/gofr/datasource/pubsub/mqtt/mqtt_test.go +++ b/pkg/gofr/datasource/pubsub/mqtt/mqtt_test.go @@ -50,7 +50,7 @@ func TestMQTT_EmptyConfigs(t *testing.T) { assert.NotNil(t, client) assert.Contains(t, out, "connected to MQTT") - assert.Contains(t, out, "Port : 1883") + assert.Contains(t, out, "Port: 1883") } func TestMQTT_getMQTTClientOptions(t *testing.T) { diff --git a/pkg/gofr/datasource/redis/redis.go b/pkg/gofr/datasource/redis/redis.go index 237fbdfd1..5d993000a 100644 --- a/pkg/gofr/datasource/redis/redis.go +++ b/pkg/gofr/datasource/redis/redis.go @@ -67,7 +67,7 @@ func NewClient(c config.Config, logger datasource.Logger, metrics Metrics) *Redi } if err := otel.InstrumentTracing(rc); err != nil { - logger.Errorf("could not add tracing instrumentation, error : %s", err) + logger.Errorf("could not add tracing instrumentation, error: %s", err) } logger.Logf("connected to redis at %s:%d", redisConfig.HostName, redisConfig.Port) diff --git a/pkg/gofr/datasource/sql/db.go b/pkg/gofr/datasource/sql/db.go index b94e54488..fb7249391 100644 --- a/pkg/gofr/datasource/sql/db.go +++ b/pkg/gofr/datasource/sql/db.go @@ -188,7 +188,7 @@ func (d *DB) Select(ctx context.Context, data interface{}, query string, args .. // First confirm that what we got in v is a pointer else it won't be settable rvo := reflect.ValueOf(data) if rvo.Kind() != reflect.Ptr { - d.logger.Error("We did not get a pointer. data is not settable.") + d.logger.Error("we did not get a pointer. data is not settable.") return } @@ -201,7 +201,7 @@ func (d *DB) Select(ctx context.Context, data interface{}, query string, args .. case reflect.Slice: rows, err := d.QueryContext(ctx, query, args...) if err != nil { - d.logger.Errorf("Error running query : %v", err) + d.logger.Errorf("error running query: %v", err) return } diff --git a/pkg/gofr/datasource/sql/db_test.go b/pkg/gofr/datasource/sql/db_test.go index d7a501194..695445581 100644 --- a/pkg/gofr/datasource/sql/db_test.go +++ b/pkg/gofr/datasource/sql/db_test.go @@ -135,7 +135,7 @@ func TestDB_SelectDataPointerError(t *testing.T) { db.Select(context.Background(), nil, "select 1") }) - assert.Contains(t, out, "We did not get a pointer. data is not settable.", "TEST Failed.\n") + assert.Contains(t, out, "we did not get a pointer. data is not settable.", "TEST Failed.\n") } func TestDB_SelectSingleColumnFromStringToCustomString(t *testing.T) { diff --git a/pkg/gofr/datasource/sql/sql.go b/pkg/gofr/datasource/sql/sql.go index cc81dcfb5..510899527 100644 --- a/pkg/gofr/datasource/sql/sql.go +++ b/pkg/gofr/datasource/sql/sql.go @@ -14,7 +14,7 @@ import ( const defaultDBPort = 3306 -var errUnsupportedDialect = fmt.Errorf("unsupported db dialect : supported dialects are - mysql, postgres") +var errUnsupportedDialect = fmt.Errorf("unsupported db dialect; supported dialects are - mysql, postgres") // DBConfig has those members which are necessary variables while connecting to database. type DBConfig struct { diff --git a/pkg/gofr/gofr.go b/pkg/gofr/gofr.go index 25892e759..06364971b 100644 --- a/pkg/gofr/gofr.go +++ b/pkg/gofr/gofr.go @@ -47,7 +47,7 @@ type App struct { // RegisterService adds a grpc service to the gofr application. func (a *App) RegisterService(desc *grpc.ServiceDesc, impl interface{}) { - a.container.Logger.Infof("Registering GRPC Server: %s", desc.ServiceName) + a.container.Logger.Infof("registering GRPC Server: %s", desc.ServiceName) a.grpcServer.server.RegisterService(desc, impl) a.grpcRegistered = true } @@ -303,7 +303,7 @@ func (a *App) EnableOAuth(jwksEndpoint string, refreshInterval int) { func (a *App) Subscribe(topic string, handler SubscribeFunc) { if a.container.GetSubscriber() == nil { - a.container.Logger.Errorf("Subscriber not initialized in the container") + a.container.Logger.Errorf("subscriber not initialized in the container") return } diff --git a/pkg/gofr/gofr_test.go b/pkg/gofr/gofr_test.go index aba4e76fd..2ff64c4c6 100644 --- a/pkg/gofr/gofr_test.go +++ b/pkg/gofr/gofr_test.go @@ -189,7 +189,7 @@ func TestApp_MigrateInvalidKeys(t *testing.T) { app.Migrate(map[int64]migration.Migrate{1: {}}) }) - assert.Contains(t, logs, `"message":"Run Failed! UP not defined for the following keys: [1]"`) + assert.Contains(t, logs, `"message":"run failed! UP not defined for the following keys: [1]"`) } func Test_otelErrorHandler(t *testing.T) { diff --git a/pkg/gofr/http/middleware/cors.go b/pkg/gofr/http/middleware/cors.go index 7d907b7c2..fdbed2e91 100644 --- a/pkg/gofr/http/middleware/cors.go +++ b/pkg/gofr/http/middleware/cors.go @@ -14,6 +14,8 @@ func CORS() func(inner http.Handler) http.Handler { return } + w.Header().Set("Access-Control-Allow-Headers", "content-type") + inner.ServeHTTP(w, r) }) } diff --git a/pkg/gofr/http/middleware/cors_test.go b/pkg/gofr/http/middleware/cors_test.go index e83ade187..50f8ba07e 100644 --- a/pkg/gofr/http/middleware/cors_test.go +++ b/pkg/gofr/http/middleware/cors_test.go @@ -23,12 +23,13 @@ func Test_CORS(t *testing.T) { handler := CORS()(&MockHandlerForCORS{statusCode: http.StatusFound, response: "Sample Response"}) tests := []struct { - method string - respBody string - respCode int + method string + respBody string + respCode int + expHeaders int }{ - {http.MethodGet, "Sample Response", http.StatusFound}, - {http.MethodOptions, "", http.StatusOK}, + {http.MethodGet, "Sample Response", http.StatusFound, 3}, + {http.MethodOptions, "", http.StatusOK, 2}, } for i, tc := range tests { @@ -38,10 +39,7 @@ func Test_CORS(t *testing.T) { assert.Equal(t, "*", w.Header().Get("Access-Control-Allow-Origin"), "TEST[%d], Failed.\n", i) assert.Equal(t, "POST, GET, OPTIONS, PUT, DELETE", w.Header().Get("Access-Control-Allow-Methods"), "TEST[%d], Failed.\n", i) - - // Check if no other headers apart from the allowed headers are being set - assert.Equal(t, 2, len(w.Header()), "TEST[%d], Failed.\n", i) - + assert.Equal(t, tc.expHeaders, len(w.Header()), "TEST[%d], Failed.\n", i) assert.Equal(t, tc.respCode, w.Code, "TEST[%d], Failed.\n", i) assert.Equal(t, tc.respBody, w.Body.String(), "TEST[%d], Failed.\n", i) } diff --git a/pkg/gofr/http/router_test.go b/pkg/gofr/http/router_test.go index 8e37d85e5..d5507ff70 100644 --- a/pkg/gofr/http/router_test.go +++ b/pkg/gofr/http/router_test.go @@ -38,6 +38,6 @@ func TestRouter(t *testing.T) { // verify if middleware logger is properly functioning inside new router if !strings.Contains(log, "\"method\":\"GET\",\"ip\":\"192.0.2.1:1234\",\"uri\":\"/test\",\"response\":200") { - t.Errorf("TestRouter Failed! expected log not found : %v", log) + t.Errorf("TestRouter Failed! expected log not found: %v", log) } } diff --git a/pkg/gofr/logging/logger.go b/pkg/gofr/logging/logger.go index 78d706a32..c1f56abea 100644 --- a/pkg/gofr/logging/logger.go +++ b/pkg/gofr/logging/logger.go @@ -6,6 +6,8 @@ import ( "io" "math" "os" + "regexp" + "strings" "time" "golang.org/x/term" @@ -155,15 +157,15 @@ func (l *logger) prettyPrint(e logEntry, out io.Writer) { e.Time.Format("15:04:05"), msg.TraceID, colorForStatusCode(msg.Response), msg.Response, msg.ResponseTime, msg.Method, msg.URI) case sql.Log: fmt.Fprintf(out, "\u001B[38;5;%dm%s\u001B[0m [%s] \u001B[38;5;8m%-32s \u001B[38;5;24m%s\u001B[0m %8d\u001B[38;5;8mµs\u001B[0m %s\n", - e.Level.color(), e.Level.String()[0:4], e.Time.Format("15:04:05"), msg.Type, "SQL", msg.Duration, msg.Query) + e.Level.color(), e.Level.String()[0:4], e.Time.Format("15:04:05"), msg.Type, "SQL", msg.Duration, clean(msg.Query)) case redis.QueryLog: if msg.Query == "pipeline" { fmt.Fprintf(out, "\u001B[38;5;%dm%s\u001B[0m [%s] \u001B[38;5;8m%-32s \u001B[38;5;24m%s\u001B[0m %6d\u001B[38;5;8mµs\u001B[0m %s\n", - e.Level.color(), e.Level.String()[0:4], e.Time.Format("15:04:05"), msg.Query, "REDIS", msg.Duration, + e.Level.color(), e.Level.String()[0:4], e.Time.Format("15:04:05"), clean(msg.Query), "REDIS", msg.Duration, msg.String()[1:len(msg.String())-1]) } else { fmt.Fprintf(out, "\u001B[38;5;%dm%s\u001B[0m [%s] \u001B[38;5;8m%-32s \u001B[38;5;24m%s\u001B[0m %6d\u001B[38;5;8mµs\u001B[0m %v\n", - e.Level.color(), e.Level.String()[0:4], e.Time.Format("15:04:05"), msg.Query, "REDIS", msg.Duration, msg.String()) + e.Level.color(), e.Level.String()[0:4], e.Time.Format("15:04:05"), clean(msg.Query), "REDIS", msg.Duration, msg.String()) } case service.Log: fmt.Fprintf(out, "\u001B[38;5;%dm%s\u001B[0m [%s] \u001B[38;5;8m%s \u001B[38;5;%dm%d\u001B[0m %8d\u001B[38;5;8mµs\u001B[0m %s %s \n", @@ -268,3 +270,10 @@ func checkIfTerminal(w io.Writer) bool { func (l *logger) changeLevel(level Level) { l.level = level } + +func clean(query string) string { + query = regexp.MustCompile(`\s+`).ReplaceAllString(query, " ") + query = strings.TrimSpace(query) + + return query +} diff --git a/pkg/gofr/logging/logger_test.go b/pkg/gofr/logging/logger_test.go index 06af3c045..8cf2483f9 100644 --- a/pkg/gofr/logging/logger_test.go +++ b/pkg/gofr/logging/logger_test.go @@ -361,3 +361,29 @@ func Test_NewSilentLoggerSTDOutput(t *testing.T) { assert.Equal(t, "", logs) } + +func Test_SQLLog(t *testing.T) { + s := sql.Log{ + Type: "Query", + Query: "Select * from \t \t \n test", + Duration: 123, + Args: nil, + } + + out := testutil.StdoutOutputForFunc(func() { + l := &logger{isTerminal: true, normalOut: os.Stdout} + l.Info(s) + }) + + assert.Contains(t, out, "Select * from test") +} + +func Test_clean(t *testing.T) { + input := `select * from + employee` + + expected := "select * from employee" + query := clean(input) + + assert.Equal(t, expected, query) +} diff --git a/pkg/gofr/metrics/register.go b/pkg/gofr/metrics/register.go index 4b77fd820..bce1ef4c2 100644 --- a/pkg/gofr/metrics/register.go +++ b/pkg/gofr/metrics/register.go @@ -237,12 +237,12 @@ func callbackFunc(name metric.Float64ObservableGauge, field float64) func(_ cont func (m *metricsManager) getAttributes(name string, labels ...string) []attribute.KeyValue { labelsCount := len(labels) if labelsCount%2 != 0 { - m.logger.Warnf("Metrics %v label has invalid key-value pairs", name) + m.logger.Warnf("metrics %v label has invalid key-value pairs", name) } cardinalityLimit := 20 if labelsCount > cardinalityLimit { - m.logger.Warnf("Metrics %v has high cardinality: %v", name, labelsCount) + m.logger.Warnf("metrics %v has high cardinality: %v", name, labelsCount) } var attributes []attribute.KeyValue diff --git a/pkg/gofr/metrics/register_test.go b/pkg/gofr/metrics/register_test.go index b9b71e10a..c5ab7ab9e 100644 --- a/pkg/gofr/metrics/register_test.go +++ b/pkg/gofr/metrics/register_test.go @@ -140,7 +140,7 @@ func Test_NewMetricsManagerInvalidLabelPairErrors(t *testing.T) { log := testutil.StdoutOutputForFunc(logs) - assert.Contains(t, log, `Metrics counter-test label has invalid key-value pairs`, "TEST Failed. Invalid key-value pair for labels") + assert.Contains(t, log, `metrics counter-test label has invalid key-value pairs`, "TEST Failed. Invalid key-value pair for labels") } func Test_NewMetricsManagerLabelHighCardinality(t *testing.T) { @@ -157,5 +157,5 @@ func Test_NewMetricsManagerLabelHighCardinality(t *testing.T) { log := testutil.StdoutOutputForFunc(logs) - assert.Contains(t, log, `Metrics counter-test has high cardinality: 24`, "TEST Failed. high cardinality of metrics") + assert.Contains(t, log, `metrics counter-test has high cardinality: 24`, "TEST Failed. high cardinality of metrics") } diff --git a/pkg/gofr/migration/migration.go b/pkg/gofr/migration/migration.go index 30a058b12..c2d7a1a80 100644 --- a/pkg/gofr/migration/migration.go +++ b/pkg/gofr/migration/migration.go @@ -23,7 +23,7 @@ type Migrate struct { func Run(migrationsMap map[int64]Migrate, c *container.Container) { invalidKeys, keys := getKeys(migrationsMap) if len(invalidKeys) > 0 { - c.Logger.Errorf("Run Failed! UP not defined for the following keys: %v", invalidKeys) + c.Logger.Errorf("run failed! UP not defined for the following keys: %v", invalidKeys) return } @@ -35,7 +35,7 @@ func Run(migrationsMap map[int64]Migrate, c *container.Container) { if c.SQL != nil { err := ensureSQLMigrationTableExists(c) if err != nil { - c.Logger.Errorf("Unable to verify sql migration table due to: %v", err) + c.Logger.Errorf("unable to verify sql migration table due to: %v", err) return } diff --git a/pkg/gofr/migration/migration_test.go b/pkg/gofr/migration/migration_test.go index 311715f31..e17527d9f 100644 --- a/pkg/gofr/migration/migration_test.go +++ b/pkg/gofr/migration/migration_test.go @@ -472,7 +472,7 @@ func Test_MigrationRedisTransactionFailure(t *testing.T) { }, cntnr) }) - assert.Contains(t, logs, "Migration for Redis redis: nil failed with err") + assert.Contains(t, logs, "migration for Redis redis: nil failed with err") } func Test_MigrationRedisUnableToGetLastRun(t *testing.T) { @@ -499,7 +499,7 @@ func Test_MigrationRedisUnableToGetLastRun(t *testing.T) { }, cntnr) }) - assert.Contains(t, logs, "Failed to get migration record from Redis : unable to get gofr_migrations") + assert.Contains(t, logs, "failed to get migration record from Redis err: unable to get gofr_migrations") } func Test_MigrationRedisGoFrDataUnmarshalFail(t *testing.T) { diff --git a/pkg/gofr/migration/redis.go b/pkg/gofr/migration/redis.go index 511725367..d6cee0fd3 100644 --- a/pkg/gofr/migration/redis.go +++ b/pkg/gofr/migration/redis.go @@ -63,7 +63,7 @@ func redisPostRun(c *container.Container, tx goRedis.Pipeliner, currentMigration _, err := tx.Exec(context.Background()) if err != nil { - c.Logger.Errorf("Migration for Redis %v failed with err : %v", err) + c.Logger.Errorf("migration for Redis %v failed with err: %v", err) } } @@ -72,7 +72,7 @@ func getRedisLastMigration(c *container.Container) int64 { table, err := c.Redis.HGetAll(context.Background(), "gofr_migrations").Result() if err != nil { - c.Logger.Errorf("Failed to get migration record from Redis : %v", err) + c.Logger.Errorf("failed to get migration record from Redis err: %v", err) return -1 } @@ -92,7 +92,7 @@ func getRedisLastMigration(c *container.Container) int64 { err = json.Unmarshal(d, &migrationData) if err != nil { - c.Logger.Errorf("Failed to unmarshal redis Migration data : %v", err) + c.Logger.Errorf("failed to unmarshal redis Migration data err: %v", err) return -1 } diff --git a/pkg/gofr/migration/sql.go b/pkg/gofr/migration/sql.go index eff94cafb..52b2d5830 100644 --- a/pkg/gofr/migration/sql.go +++ b/pkg/gofr/migration/sql.go @@ -110,7 +110,7 @@ func rollbackAndLog(c *container.Container, version int64, tx *gofrSql.Tx, err e c.Logger.Error("unable to rollback transaction: %v", err) } - c.Logger.Errorf("Migration %v rolled back", version) + c.Logger.Errorf("migration %v rolled back", version) } func sqlPostRun(c *container.Container, tx *gofrSql.Tx, currentMigration int64, start time.Time) { @@ -138,7 +138,7 @@ func sqlPostRun(c *container.Container, tx *gofrSql.Tx, currentMigration int64, return } - c.Logger.Infof("Migration %v ran successfully", currentMigration) + c.Logger.Infof("migration %v ran successfully", currentMigration) } const ( diff --git a/pkg/gofr/testutil/mock_logger_test.go b/pkg/gofr/testutil/mock_logger_test.go index 21582178a..91bf9888f 100644 --- a/pkg/gofr/testutil/mock_logger_test.go +++ b/pkg/gofr/testutil/mock_logger_test.go @@ -47,9 +47,9 @@ func Test_NewMockLoggerErrorLogs(t *testing.T) { logger := NewMockLogger(DEBUGLOG) logger.Error("ERROR Log") - logger.Errorf("Error Log with Format Value: %v", "errorf") + logger.Errorf("error Log with Format Value: %v", "errorf") }) assert.Contains(t, logs, "ERROR Log") - assert.Contains(t, logs, "Error Log with Format Value: errorf") + assert.Contains(t, logs, "error Log with Format Value: errorf") } diff --git a/pkg/gofr/version/version.go b/pkg/gofr/version/version.go index f61e5d146..9192ea4ed 100644 --- a/pkg/gofr/version/version.go +++ b/pkg/gofr/version/version.go @@ -1,3 +1,3 @@ package version -const Framework = "v1.2.0" +const Framework = "v1.2.1"