Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
wbdb committed Jul 26, 2023
1 parent 96fb442 commit a81d602
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package logger

import (
"log"
"os"
)

var Write *conditionalLogger

func init() {
Write = &conditionalLogger{
consoleLogger: log.New(os.Stdout, "", log.LstdFlags),
}
}

type conditionalLogger struct {
hasErrorOccurred bool
fileLogger *log.Logger
consoleLogger *log.Logger
logFile *os.File
}

func (c *conditionalLogger) Log(v ...interface{}) {
if c.hasErrorOccurred {
c.fileLogger.Println(v...)
} else {
c.consoleLogger.Println(v...)
}
}

func (c *conditionalLogger) Logf(format string, v ...interface{}) {
if c.hasErrorOccurred {
c.fileLogger.Printf(format, v...)
} else {
c.consoleLogger.Printf(format, v...)
}
}

func (c *conditionalLogger) Error(v ...interface{}) {
c.initFileLoggerIfNecessary()
c.fileLogger.Println(v...)
}

func (c *conditionalLogger) Errorf(format string, v ...interface{}) {
c.initFileLoggerIfNecessary()
c.fileLogger.Printf(format, v...)
}

// Private helper method to initialize the file logger if an error occurs.
func (c *conditionalLogger) initFileLoggerIfNecessary() {
if !c.hasErrorOccurred {
c.logFile, _ = os.OpenFile("log.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
c.fileLogger = log.New(c.logFile, "", log.LstdFlags)
c.hasErrorOccurred = true
}
}

0 comments on commit a81d602

Please sign in to comment.