Skip to content

Commit

Permalink
Release v1.2.1 (#409)
Browse files Browse the repository at this point in the history
* Bump google.golang.org/api from 0.170.0 to 0.171.0 (#405)

Bumps [google.golang.org/api](https://github.com/googleapis/google-api-go-client) from 0.170.0 to 0.171.0.
- [Release notes](https://github.com/googleapis/google-api-go-client/releases)
- [Changelog](https://github.com/googleapis/google-api-go-client/blob/main/CHANGES.md)
- [Commits](googleapis/google-api-go-client@v0.170.0...v0.171.0)

---
updated-dependencies:
- dependency-name: google.golang.org/api
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* add Access Control Allow Headers to CORS middleware. (#407)

* add Access Control Allow Headers to CORS middleware

* fix failing tests

* fix cors test

---------

Co-authored-by: vipul-rawat-zs <vipul.rawat@zopsmart.com>

* Remove double spaces from SQL logs and make error logs uniform (#404)

* standardising log content

* clean the sql and redis queries before logging queries

* add clean function using regex to remove unnecessary spaces in sql query

* standardize log messages

* update gofr version - 1.2.1

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Umang Mundhra <mundhraumang.02@gmail.com>
  • Loading branch information
3 people authored Mar 27, 2024
1 parent 7a1e069 commit fbe79af
Show file tree
Hide file tree
Showing 28 changed files with 103 additions and 64 deletions.
6 changes: 3 additions & 3 deletions examples/using-migrations/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
8 changes: 4 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand All @@ -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
Expand All @@ -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
)
16 changes: 8 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down Expand Up @@ -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=
Expand All @@ -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=
Expand Down
2 changes: 1 addition & 1 deletion pkg/gofr/container/health_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
6 changes: 4 additions & 2 deletions pkg/gofr/datasource/pubsub/google/google.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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,
Expand Down Expand Up @@ -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
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/gofr/datasource/pubsub/kafka/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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
}
Expand Down
6 changes: 4 additions & 2 deletions pkg/gofr/datasource/pubsub/kafka/kafka.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand All @@ -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,
Expand Down
8 changes: 4 additions & 4 deletions pkg/gofr/datasource/pubsub/mqtt/mqtt.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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()
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/gofr/datasource/pubsub/mqtt/mqtt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/gofr/datasource/redis/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions pkg/gofr/datasource/sql/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/gofr/datasource/sql/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/gofr/datasource/sql/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions pkg/gofr/gofr.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/gofr/gofr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 2 additions & 0 deletions pkg/gofr/http/middleware/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}
Expand Down
16 changes: 7 additions & 9 deletions pkg/gofr/http/middleware/cors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/gofr/http/router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
15 changes: 12 additions & 3 deletions pkg/gofr/logging/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"io"
"math"
"os"
"regexp"
"strings"
"time"

"golang.org/x/term"
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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
}
26 changes: 26 additions & 0 deletions pkg/gofr/logging/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Loading

0 comments on commit fbe79af

Please sign in to comment.