package logging import ( native `log` `os` `path` `strings` "r00t2.io/goutils/types" sysd `github.com/coreos/go-systemd/journal` `r00t2.io/sysutils/paths` ) var ( _ = sysd.Enabled() _ = native.Logger{} _ = os.Interrupt _ = types.Env{} ) func GetLogger(enableDebug bool, prefix string) (logger Logger, err error) { var logPath string var logflags types.MaskBit // Configure system-supported logger(s). if sysd.Enabled() { // Use Journald. logflags.AddFlag(LogJournald) } else { // If we can detect syslog, use that. If not, try to use a file logger (+ stdout). // Last ditch, stdout. var hasSyslog bool var stat os.FileInfo var devlogPath string = devlog if hasSyslog, stat, err = paths.RealPathExistsStat(&devlogPath); hasSyslog && err != nil {return} if hasSyslog && !stat.Mode().IsRegular() {logflags.AddFlag(LogSyslog)} else { var exists bool var success bool logflags.AddFlag(LogStdout) for _, p := range defLogPaths { if exists, _ = paths.RealPathExists(&p); exists { if success, err = testOpen(p); err != nil { continue } else if !success { continue } logflags.AddFlag(LogFile) logPath = p break } else { dirPath := path.Dir(p) if err = paths.MakeDirIfNotExist(&dirPath); err != nil { continue } if success, err = testOpen(p); err != nil { continue } else if !success { continue } logflags.AddFlag(LogFile) logPath = p break } } } } if logflags.HasFlag(LogJournald) { logger = &SystemDLogger{ Prefix: logPrefix, } } else { if logflags.HasFlag(LogSyslog) { logger = &SyslogLogger{ Prefix: logPrefix, } } else { if logflags.HasFlag(LogFile) { logger = &FileLogger{ StdLogger: StdLogger{ Prefix: logPrefix, }, Path: logPath, } } else { logger = &StdLogger{ Prefix: logPrefix, } } } } logger.doDebug(enableDebug) if strings.TrimSpace(prefix) != "" { logger.setPrefix(prefix) } return } func testOpen(path string) (success bool, err error) { var f *os.File // Example #2, https://golang.org/pkg/os/#OpenFile if f, err = os.OpenFile(path, os.O_RDWR | os.O_CREATE, logPerm); err != nil { return } defer f.Close() success = true return }