|
| 1 | +package console |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "os" |
| 6 | + "sync" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/gookit/color" |
| 10 | + "github.com/randlabs/go-logger/internal/util" |
| 11 | +) |
| 12 | + |
| 13 | +//------------------------------------------------------------------------------ |
| 14 | + |
| 15 | +var mtx = sync.Mutex{} |
| 16 | + |
| 17 | +//------------------------------------------------------------------------------ |
| 18 | + |
| 19 | +// LogError prints an error message on screen. |
| 20 | +func LogError(now time.Time, msg string, isJSON bool) { |
| 21 | + if !isJSON { |
| 22 | + logPrint(os.Stderr, color.Error, now, "ERROR", msg) |
| 23 | + } else { |
| 24 | + logPrintJSON(os.Stderr, now, "error", msg) |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +// LogWarning prints a warning message on screen. |
| 29 | +func LogWarning(now time.Time, msg string, isJSON bool) { |
| 30 | + if !isJSON { |
| 31 | + logPrint(os.Stderr, color.Warn, now, "WARNING", msg) |
| 32 | + } else { |
| 33 | + logPrintJSON(os.Stderr, now, "warning", msg) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +// LogInfo prints an information message on screen. |
| 38 | +func LogInfo(now time.Time, msg string, isJSON bool) { |
| 39 | + if !isJSON { |
| 40 | + logPrint(os.Stdout, color.Info, now, "INFO", msg) |
| 41 | + } else { |
| 42 | + logPrintJSON(os.Stdout, now, "info", msg) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +// LogDebug prints a debug message on screen. |
| 47 | +func LogDebug(now time.Time, msg string, isJSON bool) { |
| 48 | + if !isJSON { |
| 49 | + logPrint(os.Stdout, color.Debug, now, "DEBUG", msg) |
| 50 | + } else { |
| 51 | + logPrintJSON(os.Stdout, now, "debug", msg) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +//------------------------------------------------------------------------------ |
| 56 | + |
| 57 | +func logPrint(w io.Writer, theme *color.Theme, now time.Time, level string, msg string) { |
| 58 | + // Lock console access |
| 59 | + mtx.Lock() |
| 60 | + |
| 61 | + // Print the message prefixed with the timestamp and level |
| 62 | + color.Fprintf(w, "%v %v %v\n", now.Format("2006-01-02 15:04:05.000"), theme.Sprintf("[%v]", level), msg) |
| 63 | + |
| 64 | + // Unlock console access |
| 65 | + mtx.Unlock() |
| 66 | +} |
| 67 | + |
| 68 | +func logPrintJSON(w io.Writer, now time.Time, level string, msg string) { |
| 69 | + // Lock console access |
| 70 | + mtx.Lock() |
| 71 | + |
| 72 | + // Print the message with extra payload |
| 73 | + color.Fprintf(w, "%v\n", util.AddPayloadToJSON(msg, &now, level)) |
| 74 | + |
| 75 | + // Unlock console access |
| 76 | + mtx.Unlock() |
| 77 | +} |
0 commit comments