https://github.com/bgruszka/gorm-loggable
loggable plugin for gorm v2
https://github.com/bgruszka/gorm-loggable
golang gorm gorm-orm plugin
Last synced: 2 months ago
JSON representation
loggable plugin for gorm v2
- Host: GitHub
- URL: https://github.com/bgruszka/gorm-loggable
- Owner: bgruszka
- License: mit
- Created: 2020-10-30T11:19:07.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-10-30T11:59:53.000Z (over 5 years ago)
- Last Synced: 2024-06-20T16:48:47.948Z (almost 2 years ago)
- Topics: golang, gorm, gorm-orm, plugin
- Language: Go
- Homepage:
- Size: 4.88 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# gorm-loggable
Loggable plugin for gorm v2
## How to use it?
```
go get github.com/bgruszka/gorm-loggable
```
then after db init:
```go
db, err = gorm.Open(postgres.Open(databaseURL), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
```
register loggable plugin:
```go
DB.Use(loggable.New())
```
In order to track changes of your model you have to mark a model with `loggable.LoggableModel`.
```go
type Order struct {
...
loggable.LoggableModel
}
```
Next you have to specify which fields should be tracked in inserts and updates.
There are to options to use:
* to track creates:
```
loggable:"create"
```
* to track updates:
```
loggable:"update"
```
It's of course possible to track both:
```
loggable:"create,update"
```
More detailed example:
```go
type Order struct {
ID uint `gorm:"primary_key"`
UserID uint `gorm:"not null" loggable:"create"`
User User
State OrderState `gorm:"not null" loggable:"create,update"`
TotalPrice decimal.Decimal `gorm:"not null" loggable:"create"`
Items []OrderItem
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index"`
loggable.LoggableModel
}
```
All the logs will be stored in `change_logs` table using this model:
```go
type ChangeLog struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time `gorm:"DEFAULT:current_timestamp"`
Action string `gorm:"type:VARCHAR(10)"`
ObjectID string `gorm:"index;type:VARCHAR(30)"`
ObjectType string `gorm:"index;type:VARCHAR(50)"`
RawObject string `gorm:"type:JSON"`
}
```