Skip to content

Commit

Permalink
Added logging to a file. Named per-program and dated to that day.
Browse files Browse the repository at this point in the history
  • Loading branch information
vaughany committed Sep 9, 2021
1 parent 60e0066 commit a7911d5
Show file tree
Hide file tree
Showing 5 changed files with 105 additions and 8 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ bin/*
nodes.json
dist/
.github_token
codecov.yml
codecov.yml
cmd/*/logs/*
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,8 @@ Completed to-do's:
* **2021-08-06**, v0.0.5. Added ability to remove a node's data from the Receiver.
* **2021-08-07**, v0.0.6. Added timestamp to the disk-persisted data; added macOS to build file.
* **2021-08-08**, v0.0.7. Added ability to export all data as JSON.
* **2021-09-07**, v0.0.8. Lots of changes based on comments from the nice people at the Gophers Slack, including: removing init(), removing globals (some: work in progress), cleaning up the readme, adding OS logos, using GoReleaser and more linters, basic tests and benchmarks (also work in progress), new lighter dashboard and hosts web pages, and tidied up the struct used to marshal/unmarshal data.
* **2021-09-07**, v0.0.8. Lots of changes based on comments from the nice people at the Gophers Slack, including: removing init(), removing globals (some: work in progress), cleaning up the readme, adding OS logos, using GoReleaser and more linters, basic tests and benchmarks (also work in progress), new lighter dashboard and hosts web pages, and tidied up the struct used to marshal/unmarshal data.
* **2021-09-09**, v0.0.9. Added logging to a file. Creates folder in cwd, then creates a named and dated file, logs to it and stdout.

---

Expand Down
35 changes: 35 additions & 0 deletions cmd/collector/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ import (
"net/http"
"os"
"os/exec"
"os/signal"
"os/user"
"regexp"
"runtime"
"strconv"
"strings"
"syscall"
"time"
vcms "vcms/internal"
)
Expand All @@ -34,6 +36,7 @@ func main() {
debug = false
testing = false
receiverURL = "http://127.0.0.1:8080"
logName = vcms.CreateLogName(vcms.LogFolder, cmdCodename)
)

flag.BoolVar(&debug, "d", debug, "Shows debugging info")
Expand All @@ -47,6 +50,20 @@ func main() {
os.Exit(0)
}

// Opens a logfile for writing and also outputs to stdout.
vcms.CheckLogFolder(vcms.LogFolder)
lf, err := os.OpenFile(logName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0755)
if err != nil {
log.Print(err)
log.Printf("Error: Couldn't open '%s' for writing, so logging to stdout only.\n", logName)
} else {
defer lf.Close()
log.SetOutput(io.MultiWriter(os.Stdout, lf))
log.Printf("Startup: Logging to stdout and '%s'.\n", logName)
}

shutdownHandler()

log.Println(vcms.Version(cmdName))
log.Printf("%s \n", cmdDesc)
log.Printf("%s \n", vcms.AppDesc)
Expand Down Expand Up @@ -365,3 +382,21 @@ func getCPUDetails() (int, string) {

return count, speed
}

// https://stackoverflow.com/a/12571099/254146
func shutdownHandler() {
channel := make(chan os.Signal)
signal.Notify(channel, os.Interrupt, syscall.SIGTERM)
go func() {
<-channel
log.Println("Close signal detected: shutting down.")

// TODO: e.g. notify Slack, send an email etc.

log.Println("Shutdown: bye bye.")
log.Println()
log.Println()
log.Println()
os.Exit(0)
}()
}
25 changes: 21 additions & 4 deletions cmd/receiver/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"flag"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
Expand All @@ -26,7 +27,6 @@ var embeddedFiles embed.FS
var (
debug = false
nodes = make(map[string]*vcms.SystemData)
// logFile string = vcms.MakeLogName(appCodename)
)

const (
Expand Down Expand Up @@ -71,12 +71,13 @@ func main() {
cmdName = "VCMS - Receiver"
cmdDesc = "Receives data from the Collector apps, creates a web page."
cmdCodename = "vcms-receiver"
persistentStorageSaveInterval = 10 // TODO: make configurable.
persistentStorageSaveInterval = 60 // TODO: make configurable.
)

var (
version = false
receiverURL = "127.0.0.1:8080" // Don't put e.g. http:// at the start. Add this to docs.
logName = vcms.CreateLogName(vcms.LogFolder, cmdCodename)
)

flag.BoolVar(&debug, "d", debug, "Shows debugging info")
Expand All @@ -89,6 +90,18 @@ func main() {
os.Exit(0)
}

// Opens a logfile for writing and also outputs to stdout.
vcms.CheckLogFolder(vcms.LogFolder)
lf, err := os.OpenFile(logName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0755)
if err != nil {
log.Print(err)
log.Printf("Error: Couldn't open '%s' for writing, so logging to stdout only.\n", logName)
} else {
defer lf.Close()
log.SetOutput(io.MultiWriter(os.Stdout, lf))
log.Printf("Startup: Logging to stdout and '%s'.\n", logName)
}

shutdownHandler()

log.Println(vcms.Version(cmdName))
Expand Down Expand Up @@ -157,12 +170,16 @@ func shutdownHandler() {
signal.Notify(channel, os.Interrupt, syscall.SIGTERM)
go func() {
<-channel
log.Println("Close signal detected. Saving nodes to persistent storage.")
log.Println("Close signal detected: shutting down.")

log.Println("Shutdown: saving nodes to persistent storage.")
saveToPersistentStorage()
// TODO: e.g. notify Slack, send an email etc.

log.Println("Exiting.")
log.Println("Shutdown: bye bye.")
log.Println()
log.Println()
log.Println()
os.Exit(0)
}()
}
Expand Down
47 changes: 45 additions & 2 deletions internal/vcms.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package vcms

import (
"fmt"
"log"
"os"
"runtime"
"time"
)
Expand All @@ -12,11 +14,12 @@ AppXxx stores strings common to both the Collector and Receiver.
ProjectURL is the URL of the project on GitHub.
*/
const (
AppDate string = "2021-09-07"
AppVersion string = "0.0.8"
AppDate string = "2021-09-09"
AppVersion string = "0.0.9"
AppTitle string = "Vaughany's Computer Monitoring System"
ProjectURL string = "github.com/vaughany/vcms"
AppDesc string = "Description of the whole system goes here."
LogFolder string = "logs"
)

/*
Expand Down Expand Up @@ -89,3 +92,43 @@ func Version(appName string) string {
// return fmt.Sprintf("%s v%s (%s), %s.\n%s\n", appName, AppVersion, AppDate, runtime.Version(), AppDesc)
return fmt.Sprintf("%s v%s (%s), %s.", appName, AppVersion, AppDate, runtime.Version())
}

/*
CheckLogFolder checks for the existence of the log folder.
*/
func CheckLogFolder(logFolder string) bool {
if stat, err := os.Stat(logFolder); err != nil || !stat.IsDir() {
log.Printf("Log folder '%s' doesn't exist.\n", logFolder)
if !CreateLogFolder(logFolder) {
log.Printf("Error: Log folder '%s' could not be created.\n", logFolder)
return false
}
log.Printf("Log folder '%s' created.\n", logFolder)
return true
}
log.Printf("Log folder '%s' exists.\n", logFolder)
return true
}

/*
CreateLogFolder creates a log folder.
*/
func CreateLogFolder(logFolder string) bool {
err := os.Mkdir(logFolder, 0755)
if err != nil {
log.Print(err)
return false
}
return true
}

/*
CreateLogName creates and returns a name for the log file, based on the application's start date.
*/
func CreateLogName(logFolder string, cmdName string) string {
// time := time.Now().Format("2006-01-02_15-04-05")
// time := time.Now().Format("2006-01-02_15-04")
time := time.Now().Format("2006-01-02")

return fmt.Sprintf("%s/%s_%s.log", logFolder, cmdName, time)
}

0 comments on commit a7911d5

Please sign in to comment.