Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions pkg/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package logger

import (
"bytes"
"fmt"
"log"
"os"
"sync"
)

// ErrLog is the logger that is controlled by this log controller
var logger *log.Logger
var logBuffer *bytes.Buffer
var mux sync.RWMutex

const logPrefix = "[Log] "

Expand All @@ -22,6 +23,9 @@ func init() {

// DeferLogs enables the log-buffer and defers any logs from printing to the screen
func DeferLogs() {
mux.Lock()
defer mux.Unlock()

if logBuffer == nil {
logBuffer = new(bytes.Buffer)
logger = log.New(logBuffer, logPrefix, 0)
Expand All @@ -30,6 +34,9 @@ func DeferLogs() {

// ImmediateLogs flushes logs and puts logging back into immediate mode
func ImmediateLogs() {
mux.Lock()
defer mux.Unlock()

if logBuffer != nil {
os.Stderr.Write(logBuffer.Bytes())
resetLogger()
Expand All @@ -42,28 +49,46 @@ func resetLogger() {
}

func Fatalln(code int, s interface{}) {
mux.RLock()
defer mux.RUnlock()

logger.Println(s)
OsExit(code)
}

func Fatal(code int, v ...interface{}) {
mux.RLock()
defer mux.RUnlock()

logger.Print(v...)
OsExit(code)
}

func Fatalf(code int, s string, args ...interface{}) {
mux.RLock()
defer mux.RUnlock()

logger.Printf(s, args...)
OsExit(code)
}

func Println(s interface{}) {
mux.RLock()
defer mux.RUnlock()

logger.Println(s)
}

func Print(v ...interface{}) {
mux.RLock()
defer mux.RUnlock()

logger.Print(v...)
}

func Printf(s string, args ...interface{}) {
Println(fmt.Sprintf(s, args...))
mux.RLock()
defer mux.RUnlock()

logger.Printf(s, args...)
}