Skip to content

Commit

Permalink
Set up rotation of logs.
Browse files Browse the repository at this point in the history
  • Loading branch information
patfair committed Jan 21, 2024
1 parent 4714bdd commit e247d1f
Showing 1 changed file with 33 additions and 10 deletions.
43 changes: 33 additions & 10 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@ import (
"os"
)

const logFilePath = "/tmp/frc-radio-api.log"
const (
// Path of the current log file.
logFilePath = "/root/frc-radio-api.log"

// Path of the old log file, which is rotated when the current log file gets too big.
oldLogFilePath = "/root/frc-radio-api.log.old"

// Maximum size of the current log file in bytes.
logFileMaxSizeBytes = 3 * 1 << 19 // 1.5 MB
)

func main() {
// Set up logging to file.
logFile, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
if err == nil {
defer logFile.Close()
log.SetOutput(logFile)
} else {
log.Printf("error opening log file; logging to stdout instead: %v", err)
}
log.Println("Starting FRC Radio API...")
setupLogging()

radio := radio.NewRadio()

Expand All @@ -29,3 +30,25 @@ func main() {
// Run the radio event loop in the main thread.
radio.Run()
}

// setupLogging sets up logging to a file, or to stdout if the file can't be opened.
func setupLogging() {
// Rotate the log file if the current one is too big.
if fileInfo, err := os.Stat(logFilePath); err == nil {
if fileInfo.Size() >= logFileMaxSizeBytes {
if err := os.Rename(logFilePath, oldLogFilePath); err != nil {
log.Printf("error rotating log file: %v", err)
}
}
}

logFile, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
if err == nil {
defer logFile.Close()
log.SetOutput(logFile)
} else {
log.Printf("error opening log file; logging to stdout instead: %v", err)
}
log.Println("Starting FRC Radio API...")

}

0 comments on commit e247d1f

Please sign in to comment.