Skip to content

Commit

Permalink
feat(logs): add log generation functionality in the log folder
Browse files Browse the repository at this point in the history
  • Loading branch information
golnar-boosty committed Nov 19, 2024
1 parent 27794c6 commit 782a358
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 0 deletions.
31 changes: 31 additions & 0 deletions logs/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package log

import (
"fmt"
"os"
"strconv"
"time"

cosmosLog "cosmossdk.io/log"
)

func CustomLogger() cosmosLog.Logger {

printLogs, err := strconv.ParseBool(os.Getenv("PrintLogs"))
if err != nil {
fmt.Println("[CustomLogger] Error parsing PrintLogs environment variable:", err)
}

if !printLogs {
return cosmosLog.NewNopLogger()
}

// Initialize a new `cosmosLog` logger instance
logger := cosmosLog.NewLogger(os.Stderr)

logger = logger.With(
"timestamp", time.Now().UTC().Format(time.RFC3339),
)

return logger
}
54 changes: 54 additions & 0 deletions logs/monitor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package log

import (
"fmt"
"os"
"runtime"
"strconv"
"time"

"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem"
"github.com/sirupsen/logrus"
)

var log = logrus.New()

// Monitor will continuously collect system information
func Monitor(interval time.Duration) {

printLogs, err := strconv.ParseBool(os.Getenv("PrintLogs"))

if err != nil {
fmt.Println("[CustomLogger] Error parsing PrintLogs environment variable:", err)
}

if printLogs {
for {
var memStats runtime.MemStats
runtime.ReadMemStats(&memStats)

v, _ := mem.VirtualMemory()
cpuPercent, _ := cpu.Percent(0, true)
loadAvg, _ := load.Avg()

log.Printf("Timestamp: %v", time.Now().Format(time.RFC3339))

log.Printf("Memory Total: %v, Free: %v, Used Percent: %.2f%%, Active: %v",
v.Total, v.Free, v.UsedPercent, v.Active)

log.Printf("CPU Usage Percentage: %v%%, CPU Usage: %v", cpuPercent, runtime.NumCPU())

// It logs the system load average for 1, 5, and 15 minutes.
log.Printf("Load Average: 1m: %.2f, 5m: %.2f, 15m: %.2f",
loadAvg.Load1, loadAvg.Load5, loadAvg.Load15)

log.Printf("Memory Alloc: %v, Total Memory Alloc: %v, System Memory: %v",
memStats.Alloc, memStats.TotalAlloc, memStats.Sys)

time.Sleep(interval)
}
}

}
14 changes: 14 additions & 0 deletions logs/recover.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package log

import (
"github.com/sirupsen/logrus"
)

var logger = logrus.New()

// Recovery function to handle panics
func RecoverFromPanic() {
if r := recover(); r != nil {
logger.Errorf("Application crashed: %v", r)
}
}

0 comments on commit 782a358

Please sign in to comment.