feat(v0.0.2): start building logging client To be consistent in the decision to keep the scope of watchman limited to development phase only. I am avoiding using kafka and instead using local json file which will sync at specified intervals. Currently the client library only manages printing and storing logs in a json file, will add features for syncing the file with remote db in coming versions.
Brijesh ops@brijesh.dev
Wed, 03 Jul 2024 13:12:44 +0530
A
async.go
@@ -0,0 +1,27 @@
+package watchman_client + +import ( + "fmt" + "os" + "time" +) + +func BackgroundLogSync(seconds int) { + ticker := time.NewTicker(time.Duration(seconds) * time.Second) + defer ticker.Stop() + + for range ticker.C { + if IsLogFileEmpty() { + fmt.Println("Log file is empty") + } else { + fmt.Println("Log file is not empty, but sync function is not built yet") + } + } +} + +func IsLogFileEmpty() bool { + file, _ := os.Open("log.json") + defer file.Close() + fileInfo, _ := file.Stat() + return fileInfo.Size() == 0 +}
A
go.sum
@@ -0,0 +1,2 @@
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
A
logger.go
@@ -0,0 +1,52 @@
+package watchman_client + +import ( + "fmt" + "os" +) + +type LoggerProps struct { + UUID string `json:"uuid"` + Level string `json:"level"` + Message string `json:"message"` + Subject string `json:"subject"` + SyncStatus string `json:"sync_status"` + Timestamp int64 `json:"timestamp"` +} + +func LoggerInit() { + CreateLogFile() +} + +func CreateLogFile() { + if _, err := os.Stat("log.json"); os.IsNotExist(err) { + fmt.Println("Creating log.json file") + file, _ := os.Create("log.json") + defer file.Close() + } else { + fmt.Println("log.json file already exists") + } +} + +func WriteLog(log LoggerProps) { + file, _ := os.OpenFile("log.json", os.O_APPEND|os.O_WRONLY, 0644) + defer file.Close() + + jsonStyleString := fmt.Sprintf("{\"uuid\": \"%v\", \"level\": \"%v\", \"message\": \"%v\", \"subject\": \"%v\", \"sync_status\": \"%v\", \"timestamp\": %v}", log.UUID, log.Level, log.Message, log.Subject, log.SyncStatus, log.Timestamp) + fmt.Fprintf(file, "%v\n", jsonStyleString) +} + +func PrintLog(log LoggerProps) { + fmt.Printf( + "%v [%v] %v: %v\n", + TimeStampToHumanReadable(log.Timestamp), + log.Level, + log.Subject, + log.Message, + ) +} + +func Log(log LoggerProps) { + PrintLog(log) + WriteLog(log) +}
A
utils.go
@@ -0,0 +1,18 @@
+package watchman_client + +import ( + "time" + + "github.com/google/uuid" +) + +func GenerateUUID() string { + return uuid.New().String() +} + +func TimeStampToHumanReadable(timestamp int64) string { + t := time.Unix(timestamp, 0) + dateFormat := "2006-01-02 15:04:05" + + return t.Format(dateFormat) +}