64 lines
1.3 KiB
Go
64 lines
1.3 KiB
Go
|
package sql
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"log"
|
||
|
"os"
|
||
|
"path"
|
||
|
"path/filepath"
|
||
|
"time"
|
||
|
|
||
|
"git.apinb.com/bsm-sdk/engine/utils"
|
||
|
"git.apinb.com/bsm-sdk/engine/vars"
|
||
|
"gorm.io/gorm/logger"
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
F *os.File
|
||
|
)
|
||
|
|
||
|
func setLogger(serviceName string, stdout bool) logger.Interface {
|
||
|
|
||
|
// create log dir
|
||
|
absPath := path.Join(utils.GetCurrentPath(), vars.SqlLogDir, serviceName)
|
||
|
if !utils.PathExists(absPath) {
|
||
|
os.MkdirAll(absPath, os.ModePerm)
|
||
|
}
|
||
|
|
||
|
// open log file
|
||
|
fullPath := getLogFileFullPath(absPath, getLogFileName(serviceName))
|
||
|
F = openLogFile(fullPath)
|
||
|
|
||
|
// write log
|
||
|
var multiOutput io.Writer
|
||
|
if stdout {
|
||
|
multiOutput = io.MultiWriter(os.Stdout, F)
|
||
|
} else {
|
||
|
multiOutput = io.MultiWriter(F)
|
||
|
}
|
||
|
|
||
|
return logger.New(log.New(multiOutput, "\r\n", log.LstdFlags), logger.Config{
|
||
|
SlowThreshold: 200 * time.Millisecond,
|
||
|
IgnoreRecordNotFoundError: false,
|
||
|
Colorful: false,
|
||
|
})
|
||
|
}
|
||
|
|
||
|
func getLogFileName(serviceName string) string {
|
||
|
return fmt.Sprintf("sql_%s.%s", time.Now().Format(vars.YYYYMMDD), vars.SqlLogFileExt)
|
||
|
}
|
||
|
|
||
|
func getLogFileFullPath(dir, fn string) string {
|
||
|
return filepath.Join(dir, fn)
|
||
|
}
|
||
|
|
||
|
func openLogFile(filePath string) *os.File {
|
||
|
handle, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||
|
if err != nil {
|
||
|
log.Printf("Fail to OpenFile :%v", err)
|
||
|
}
|
||
|
|
||
|
return handle
|
||
|
}
|