SoFunction
Updated on 2025-03-05

Golang xorm log writing operation to file

golang access database record SQL statement:

The packages used are:

1: /arthurkiller/rollingwriter //write to log package

2: /go-xorm/xorm //xorm package

The specific implementation is:

package main 
import (
 "time"
 
 "/arthurkiller/rollingwriter"
 _ "/go-sql-driver/mysql"
 "/go-xorm/xorm"
)
 
func main() {
 var conn string = "root:123456@tcp(127.0.0.1)/logsdemo?charset=utf-8"
 Engine, err := ("mysql", conn)
 if err != nil {
 panic("mysql connect fail")
 }
 config := {
 LogPath: "./logs", //Log path TimeTagFormat: "060102150405", //Time format string FileName: "mysql_exec", //Log file name MaxRemain: 3,  //Configure the maximum number of logs to be retained RollingPolicy: , //Configure rolling policy norolling t imerolling volumerolling
 RollingTimePattern: "* * * * * *",  //Configure the time scrolling strategy RollingVolumeSize: "1M",   //Configure the lower limit size of the truncated file WriterMode: "none",
 BufferWriterThershould: 256,
 // Compress will compress log file with gzip
 Compress: true,
 }
 
 writer, err := (&config)
 if err != nil {
 panic(err)
 }
 
 var logger * = (writer) 
 (logger)
 (true) 
 ("ts info code") 
 ("select * from cp_order where id = ? ", 3)
 (1 * )
 
}

rollingwriter implements a log write in xorm, saves logs into files in rollingwriter

Dependency package:/robfig/cron

Supplement: golang xorm Model Model File Template

*

package models 
import (
 "fmt"
 "/go-xorm/xorm"
 "time"
)
 
// User login for the first timetype FirstLoginRecord struct {
 Id int64 `xorm:"not null pk autoincr INT(11)"`
 UserID int64 `json:"userid" xorm:"int(11) not null 'userid'"`
 IP string `json:"logonip" xorm:"varchar(45) not null 'logonip'"`
 CreatedAt  `json:"logontime" xorm:"timestamp not null 'logontime'"`
 UpdatedAt  `json:"logofftime" xorm:"timestamp not null 'logofftime'"`
 Source int `json:"source" xorm:"tinyint(3) not null"`
 IsCharged int `json:"ischargeaccount" xorm:"tinyint(3) unsigned not null 'ischargeaccount'"`
}
 
func (*FirstLoginRecord) TableName() string {
 return "W_UserFirstLogonRec"
}
 
func (*FirstLoginRecord) DB() * {
 return DbDefault()
}
 
func (t *FirstLoginRecord) Save() error {
 var err error
 var engine = ()
 if  == 0 {
 , err = (t)
 return err
 }
 var rowsAffected int64
 rowsAffected, err = ().Update(t)
 ("@table: %s: %d rows affected", (), rowsAffected)
 return err
}
 
// Unique constraint for user idfunc (this *FirstLoginRecord) AddDistinct() error {
 var err error
 var engine = ()
 var has bool
 var ent = FirstLoginRecord{UserID:  }
 has, err = (&ent)
 if has {
 return nil
 }
 , err = (this)
 return err
}

/docs/

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.