Created
July 26, 2016 11:33
-
-
Save petruisfan/53fcffff6b5cd3a1e713c78131f39bed to your computer and use it in GitHub Desktop.
Logger implemented using default log package
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package logger | |
import ( | |
"log" | |
"os" | |
"some/config" | |
) | |
var ( | |
fileLogger *log.Logger | |
consoleLogger *log.Logger | |
print2Console bool | |
printDebug bool | |
) | |
func Init(conf config.Configuration ) { | |
print2Console = conf.Console | |
printDebug = conf.Debug | |
// | |
// Verify log folder exists | |
// | |
_, err := os.Stat(conf.LogFolder) | |
if os.IsNotExist(err) { | |
err = os.MkdirAll(conf.LogFolder, 0755) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
f, err := os.OpenFile(conf.LogFolder + conf.LogFile, os.O_RDWR | os.O_CREATE | os.O_APPEND, 0644) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fileLogger = log.New(f, "", log.LstdFlags|log.Lshortfile) | |
consoleLogger = log.New(os.Stdout, "", log.LstdFlags|log.Lshortfile) | |
} | |
func Debug(msg string) { | |
if printDebug { | |
fileLogger.Printf("DEBUG %s\n", msg) | |
if print2Console { | |
consoleLogger.Printf("DEBUG %s\n", msg) | |
} | |
} | |
} | |
func Warn(msg string) { | |
fileLogger.Printf("WARN %s\n", msg) | |
if print2Console { | |
consoleLogger.Printf("WARN %s\n", msg) | |
} | |
} | |
func Error(msg string) { | |
fileLogger.Printf("ERROR %s\n", msg) | |
if print2Console { | |
consoleLogger.Printf("ERROR %s\n", msg) | |
} | |
} | |
func Fatal(msg string) { | |
if print2Console { | |
consoleLogger.Printf("FATAL %s\n", msg) | |
} | |
fileLogger.Fatalf("FATAL %s\n", msg) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "logger" | |
func main() { | |
logger.Init(conf) | |
logger.Debug("Logger initialized") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment