f5/syslog.go
2023-08-13 10:31:04 +08:00

143 lines
2.8 KiB
Go

package f5
import (
"os"
"sync"
"time"
"fmt"
"q5"
)
const (
LOG_DEBUG = 0
LOG_INFO = iota
LOG_NOTICE = iota
LOG_WARNING = iota
LOG_ERROR = iota
LOG_ALERT = iota
LOG_EMERGENCY = iota
)
const SYS_LOG_ROOT = "/data/logs/%s/logs/"
const SYS_LOG_FILENAME = "log_%d_%s.log"
type LogMsgNode struct {
logMsg string
next *LogMsgNode
}
type SysLog_ struct {
logLevel int32
topNode *LogMsgNode
botNode *LogMsgNode
msgMutex sync.Mutex
chGoSaveExit chan int
}
func (this *SysLog_) Init() {
this.chGoSaveExit = make(chan int)
go this.goSaveToFile()
}
func (this *SysLog_) UnInit() {
this.chGoSaveExit <- 1
}
func (this *SysLog_) Emergency(format string, args ...interface{}) {
if this.logLevel > LOG_EMERGENCY {
return
}
this.addLog("[EMERGENCY]", format, args...)
}
func (this *SysLog_) Alert(format string, args ...interface{}) {
if this.logLevel > LOG_ALERT {
return
}
this.addLog("[ALERT]", format, args...)
}
func (this *SysLog_) Error(format string, args ...interface{}) {
if this.logLevel > LOG_ERROR {
return
}
this.addLog("[ERROR]", format, args...)
}
func (this *SysLog_) Warning(format string, args ...interface{}) {
if this.logLevel > LOG_WARNING {
return
}
this.addLog("[WARNING]", format, args...)
}
func (this *SysLog_) Notice(format string, args ...interface{}) {
if this.logLevel > LOG_NOTICE {
return
}
this.addLog("[NOTICE]", format, args...)
}
func (this *SysLog_) Info(format string, args ...interface{}) {
if this.logLevel > LOG_INFO {
return
}
this.addLog("[INFO]", format, args...)
}
func (this *SysLog_) Debug(format string, args ...interface{}) {
if this.logLevel > LOG_DEBUG {
return
}
this.addLog("[DEBUG]", format, args...)
}
func (this *SysLog_) addLog(category string, format string, args ...interface{}) {
p := &LogMsgNode{}
p.logMsg = time.Now().Format("2006-01-02 15:04:05") +
category + " " +
fmt.Sprintf(format, args...) + "\n"
/*if q5.Debug() {
fmt.Print(p.logMsg)
}*/
this.msgMutex.Lock()
defer this.msgMutex.Unlock()
if this.botNode != nil {
this.botNode.next = p
this.botNode = p
} else {
this.topNode = p
this.botNode = p
}
}
func (this *SysLog_) goSaveToFile() {
var workNode *LogMsgNode
for {
select {
case <-this.chGoSaveExit:
return
case <-time.After(time.Millisecond * 10):
}
this.msgMutex.Lock()
workNode = this.topNode
this.topNode = nil
this.botNode = nil
this.msgMutex.Unlock()
if workNode != nil {
logDir := fmt.Sprintf(SYS_LOG_ROOT, App().GetPkgName())
fileName := fmt.Sprintf(TGLOG_FILENAME, os.Getpid(), time.Now().Format("20060102"))
q5.ForceCreateDir(logDir)
if f, err := os.OpenFile(logDir + fileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666); err == nil {
for workNode != nil {
f.Write([]byte(workNode.logMsg))
workNode = workNode.next
}
f.Close()
} else {
fmt.Println(err)
}
}
}
}