您的位置:首页技术文章

golang xorm日志写入文件中的操作

【字号: 日期:2023-11-21 16:09:22浏览:3作者:馨心

golang访问数据库记录SQL语句:

使用的包为:

1:github.com/arthurkiller/rollingwriter //写入日志包

2: github.com/go-xorm/xorm //xorm包

具体实现为:

package main import ( 'time' 'github.com/arthurkiller/rollingwriter' _ 'github.com/go-sql-driver/mysql' 'github.com/go-xorm/xorm') func main() { var conn string = 'root:123456@tcp(127.0.0.1)/logsdemo?charset=utf-8' Engine, err := xorm.NewEngine('mysql', conn) if err != nil { panic('mysql connect fail') } config := rollingwriter.Config{ LogPath: './logs', //日志路径 TimeTagFormat: '060102150405', //时间格式串 FileName: 'mysql_exec', //日志文件名 MaxRemain: 3, //配置日志最大存留数 RollingPolicy: rollingwriter.VolumeRolling, //配置滚动策略 norolling t imerolling volumerolling RollingTimePattern: '* * * * * *', //配置时间滚动策略 RollingVolumeSize: '1M', //配置截断文件下限大小 WriterMode: 'none', BufferWriterThershould: 256, // Compress will compress log file with gzip Compress: true, } writer, err := rollingwriter.NewWriterFromConfig(&config) if err != nil { panic(err) } var logger *xorm.SimpleLogger = xorm.NewSimpleLogger(writer) Engine.SetLogger(logger) Engine.ShowSQL(true) logger.Info('ts info code') Engine.Exec('select * from cp_order where id = ? ', 3) time.Sleep(1 * time.Second) }

rollingwriter 实现一个 io.Writer传入到xorm.NewSimpleLogger 中 在xorm中实现日志的写入,在rollingwriter中保存日志到文件中

依赖包:https://github.com/robfig/cron

补充: golang xorm Model 模型文件模板

* Record.go

package models import ( 'fmt' 'github.com/go-xorm/xorm' 'time') // 用户首次登录type 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 time.Time `json:'logontime' xorm:'timestamp not null ’logontime’'` UpdatedAt time.Time `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() *xorm.Engine { return DbDefault()} func (t *FirstLoginRecord) Save() error { var err error var engine = t.DB() if t.Id == 0 { t.Id, err = engine.Insert(t) return err } var rowsAffected int64 rowsAffected, err = engine.Id(t.Id).Update(t) fmt.Printf('@table: %s: %d rows affected', t.TableName(), rowsAffected) return err} // 用户id唯一约束func (this *FirstLoginRecord) AddDistinct() error { var err error var engine = this.DB() var has bool var ent = FirstLoginRecord{UserID: this.UserID } has, err = engine.Get(&ent) if has { return nil } this.Id, err = engine.Insert(this) return err}

http://www.xorm.io/docs/

以上为个人经验,希望能给大家一个参考,也希望大家多多支持优爱好网。如有错误或未考虑完全的地方,望不吝赐教。

标签: Golang
相关文章: