Skip to content

Commit

Permalink
refactor(logging): add routine to create and use log file based on ap…
Browse files Browse the repository at this point in the history
…p start time
  • Loading branch information
jeamon committed Nov 11, 2023
1 parent 1c99df8 commit 8712bcc
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
16 changes: 11 additions & 5 deletions app.core.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,19 @@ type App struct {
}

// NewApp provides an instance of App.
func NewApp() (AppProvider, error) {
func NewApp(start time.Time) (AppProvider, error) {
var app *App
config, err := LoadAndInitConfigs(GitCommit, GitTag, BuildTime)
if err != nil {
return nil, fmt.Errorf("failed to setup app configuration: %s", err)
}

// ensure the logs folder exists and Setup the logging module.
err = os.MkdirAll(filepath.Dir(config.LogFile), 0o700)
err = os.MkdirAll(config.LogFolder, 0o700)
if err != nil {
return nil, fmt.Errorf("failed to create logging folder: %s", err)
return nil, fmt.Errorf("logging: failed to create folder: %v", err)
}
logFile, err := os.OpenFile(config.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
logFile, err := os.OpenFile(createLogFilePath(config.LogFolder, start), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return nil, fmt.Errorf("failed to create logging file: %s", err)
}
Expand Down Expand Up @@ -76,7 +76,7 @@ func NewApp() (AppProvider, error) {
boltDBConsumer := NewBoltDBConsumer(logger, redisQueue, boltBookStorage)

bookService := NewBookService(logger, config, NewClock(), redisBookStorage, boltBookStorage, redisQueue)
stats := NewStatistics(config.GitTag, config.GitCommit, runtime.Version(), runtime.GOOS+"/"+runtime.GOARCH, IsAppRunningInDocker(), time.Now())
stats := NewStatistics(config.GitTag, config.GitCommit, runtime.Version(), runtime.GOOS+"/"+runtime.GOARCH, IsAppRunningInDocker(), start)
apiService := NewAPIHandler(logger, config, stats, NewClock(), NewIDsHandler(), bookService)

// Build the map of middlewares stacks.
Expand Down Expand Up @@ -211,3 +211,9 @@ func (app *App) ConsumeQueues(gCtx context.Context, g *errgroup.Group) func() er
return nil
}
}

// createLogFilePath returns the absolute path of the initial log file.
func createLogFilePath(folder string, t time.Time) string {
suffix := fmt.Sprintf("%02d%02d%02d.%02d%02d%02d.log", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
return filepath.Join(folder, suffix)
}
3 changes: 2 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package main

import (
"log"
"time"
)

func main() {
app, err := NewApp()
app, err := NewApp(time.Now())
if err != nil {
log.Fatalf("app failed: %v", err)
}
Expand Down

0 comments on commit 8712bcc

Please sign in to comment.