Skip to content

Commit

Permalink
feat: create new log file when too many logs recorded
Browse files Browse the repository at this point in the history
  • Loading branch information
songquanpeng committed Sep 17, 2023
1 parent fe26a14 commit 4335f00
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
28 changes: 26 additions & 2 deletions common/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"log"
"os"
"path/filepath"
"sync"
"time"
)

Expand All @@ -17,9 +18,24 @@ const (
loggerError = "ERR"
)

func SetupGinLog() {
const maxLogCount = 1000000

var logCount int
var setupLogLock sync.Mutex
var setupLogWorking bool

func SetupLogger() {
if *LogDir != "" {
logPath := filepath.Join(*LogDir, fmt.Sprintf("oneapi-%s.log", time.Now().Format("20060102150405")))
ok := setupLogLock.TryLock()
if !ok {
log.Println("setup log is already working")
return
}
defer func() {
setupLogLock.Unlock()
setupLogWorking = false
}()
logPath := filepath.Join(*LogDir, fmt.Sprintf("oneapi-%s.log", time.Now().Format("20060102")))
fd, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal("failed to open log file")
Expand Down Expand Up @@ -59,6 +75,14 @@ func logHelper(ctx context.Context, level string, msg string) {
id := ctx.Value(RequestIdKey)
now := time.Now()
_, _ = fmt.Fprintf(writer, "[%s] %v | %s | %s \n", level, now.Format("2006/01/02 - 15:04:05"), id, msg)
logCount++ // we don't need accurate count, so no lock here
if logCount > maxLogCount && !setupLogWorking {
logCount = 0
setupLogWorking = true
go func() {
SetupLogger()
}()
}
}

func FatalLog(v ...any) {
Expand Down
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ var buildFS embed.FS
var indexPage []byte

func main() {
common.SetupGinLog()
common.SetupLogger()
common.SysLog("One API " + common.Version + " started")
if os.Getenv("GIN_MODE") != "debug" {
gin.SetMode(gin.ReleaseMode)
Expand Down

0 comments on commit 4335f00

Please sign in to comment.