Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable default error logger in Go-Gorm

I am using GORM with MySQL, I have encountered and handled the error Error 1062: Duplicate entry. The problem is that it's still printed to the console.

Code in gym/models/auth.go:49:

func AddAuth(username, password string) error {
    passwordHash, err := auth.HashPassword(password, argon2Conf)
    if err != nil {
        return err
    }
    userAuth := Auth{
        Username: username,
        Password: passwordHash,
    }
    return db.Create(&userAuth).Error
}

I am handling the error in the handler function:

func SignUpHandler(c *gin.Context) {
    var form user
    if err := c.ShouldBind(&form); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    if err := models.AddAuth(form.Username, form.Password); err == nil {
        c.JSON(http.StatusOK, gin.H{"status": "you are signed in"})
    } else {
        // I think I have handled the sql error here
        c.JSON(http.StatusBadRequest, gin.H{"error": "sign in failed"})
    }
}

When I send a POST request, the error is correctly handled and I get the correct response with {"error": "sign in failed"}. But the console still prints this error message:

(/...../gym/models/auth.go:49) 
[2019-04-28 23:37:06]  Error 1062: Duplicate entry '123123' for key 'username' 
[GIN] 2019/04/28 - 23:37:06 | 400 |  136.690908ms |             ::1 | POST     /signup

I am confused since I handled the error but it still gets printed. How to prevent this error from getting printed to the error log? Or am I handle the error correct?

like image 746
Li Jinyao Avatar asked Apr 28 '19 16:04

Li Jinyao


People also ask

Is Gorm slow?

Gorm seem to be extremely slow. The last time takes almost 60s to query. Whereas if I used "database/sql" mysql. QueryRow() its less than 500ms.

How do I log a query in Gorm?

Current state of logging in GORM In order to enable logging for all queries, we need to invoke the LogMode method with true as the argument. The logs below are for a simple /GET API call which retrieves records from the orders and items table.

What is Gorm Golang?

The GORM is fantastic ORM library for Golang, aims to be developer friendly. It is an ORM library for dealing with relational databases. This gorm library is developed on the top of database/sql package. The overview and feature of ORM are: Full-Featured ORM (almost)


1 Answers

UPDATE: for gorm v2:

Use the Logger in gorm.Config:

db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
  Logger: logger.Default.LogMode(logger.Silent),
})

For gorm v1:

Use db.LogMode to silence the default error logger.

LogMode set log mode, true for detailed logs, false for no log, default, will only print error logs.

db.LogMode(false) should do the job!

like image 183
ifnotak Avatar answered Oct 02 '22 02:10

ifnotak