2022-10-13 17:03:36 +00:00
|
|
|
package logging
|
|
|
|
|
2023-01-17 06:55:28 +00:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2023-02-02 05:45:23 +00:00
|
|
|
"strings"
|
|
|
|
"time"
|
2023-01-17 06:55:28 +00:00
|
|
|
|
|
|
|
"github.com/rs/zerolog"
|
2023-02-02 05:45:23 +00:00
|
|
|
"gopkg.in/natefinch/lumberjack.v2"
|
2023-01-17 06:55:28 +00:00
|
|
|
)
|
|
|
|
|
2022-10-13 17:14:26 +00:00
|
|
|
type Logging struct {
|
|
|
|
Err error
|
|
|
|
Output string
|
|
|
|
}
|
|
|
|
|
2022-11-23 05:20:08 +00:00
|
|
|
type Logfile struct {
|
|
|
|
LogfilePath string
|
|
|
|
}
|
2023-01-17 06:55:28 +00:00
|
|
|
|
|
|
|
func ExitWithMSG(msg string, code int, log *zerolog.Logger) {
|
|
|
|
fmt.Printf("%s\n", msg)
|
|
|
|
os.Exit(code)
|
|
|
|
}
|
2023-02-02 05:45:23 +00:00
|
|
|
|
2023-02-12 05:50:19 +00:00
|
|
|
func SetLoggingWriters(logFile string) (writers zerolog.LevelWriter) {
|
2023-02-02 05:45:23 +00:00
|
|
|
|
|
|
|
console := zerolog.ConsoleWriter{}
|
|
|
|
if IsConsoleLoggingEnabled() {
|
|
|
|
|
|
|
|
console = zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC1123}
|
|
|
|
console.FormatLevel = func(i interface{}) string {
|
|
|
|
return strings.ToUpper(fmt.Sprintf("| %-6s|", i))
|
|
|
|
}
|
|
|
|
console.FormatMessage = func(i any) string {
|
|
|
|
if i == nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("MSG: %s", i)
|
|
|
|
}
|
|
|
|
console.FormatFieldName = func(i interface{}) string {
|
|
|
|
return fmt.Sprintf("%s: ", i)
|
|
|
|
}
|
|
|
|
console.FormatFieldValue = func(i interface{}) string {
|
|
|
|
return fmt.Sprintf("%s", i)
|
|
|
|
// return strings.ToUpper(fmt.Sprintf("%s", i))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fileLogger := &lumberjack.Logger{
|
|
|
|
MaxSize: 500, // megabytes
|
|
|
|
MaxBackups: 3,
|
|
|
|
MaxAge: 28, //days
|
|
|
|
Compress: true, // disabled by default
|
|
|
|
}
|
2023-02-12 05:50:19 +00:00
|
|
|
fileLogger.Filename = logFile
|
2023-02-02 05:45:23 +00:00
|
|
|
// UNIX Time is faster and smaller than most timestamps
|
|
|
|
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
|
|
|
|
// zerolog.TimeFieldFormat = time.RFC1123
|
|
|
|
writers = zerolog.MultiLevelWriter(fileLogger)
|
|
|
|
|
|
|
|
if IsConsoleLoggingEnabled() {
|
|
|
|
writers = zerolog.MultiLevelWriter(console, fileLogger)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func IsConsoleLoggingEnabled() bool {
|
|
|
|
return os.Getenv("BACKY_CONSOLE_LOGGING") == "enabled"
|
|
|
|
}
|
2023-02-12 05:50:19 +00:00
|
|
|
|
|
|
|
// func IsTerminal() bool {
|
|
|
|
// return os.Getenv("BACKY_TERM") == "enabled"
|
|
|
|
// }
|