Skip to content

Commit 29c2a5b

Browse files
committed
add env for logging to file (fix #22) and syslog
1 parent f2bdd6b commit 29c2a5b

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

oldlog.go

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,13 @@ var defaultLogFormat = "color"
3131

3232
// Logging environment variables
3333
const (
34+
// TODO these env names should be more general, IPFS is not the only project to
35+
// use go-log
3436
envLogging = "IPFS_LOGGING"
3537
envLoggingFmt = "IPFS_LOGGING_FMT"
38+
39+
envLoggingFile = "GOLOG_FILE" // /path/to/file
40+
envLoggingSyslog = "GOLOG_SYSLOG_ENABLE" // 1 or 0
3641
)
3742

3843
// ErrNoSuchLogger is returned when the util pkg is asked for a non existant logger
@@ -43,15 +48,43 @@ var loggerMutex sync.RWMutex
4348
var loggers = map[string]*logging.Logger{}
4449

4550
// SetupLogging will initialize the logger backend and set the flags.
51+
// TODO calling this in `init` pushes all configuration to env variables
52+
// - move it out of `init`? then we need to change all the code (js-ipfs, go-ipfs) to call this explicitly
53+
// - have it look for a config file? need to define what that is
4654
func SetupLogging() {
4755

56+
// colorful or plain
4857
lfmt := LogFormats[os.Getenv(envLoggingFmt)]
4958
if lfmt == "" {
5059
lfmt = LogFormats[defaultLogFormat]
5160
}
5261

53-
backend := logging.NewLogBackend(colorable.NewColorableStderr(), "", 0)
54-
logging.SetBackend(backend)
62+
// check if we log to a file, or syslog, building a list of log backends
63+
var lgbe []logging.Backend
64+
if logfp := os.Getenv(envLoggingFile); len(logfp) > 0 {
65+
f, err := os.Create(logfp)
66+
if err != nil {
67+
fmt.Fprintf(os.Stderr, "ERROR go-log: %s: failed to set logging file backend\n", err)
68+
} else {
69+
lgbe = append(lgbe, logging.NewLogBackend(f, "", 0))
70+
}
71+
}
72+
73+
// check if we want a syslogger
74+
if env := os.Getenv(envLoggingSyslog); env == "1" {
75+
slbe, err := logging.NewSyslogBackend("")
76+
if err != nil {
77+
fmt.Fprintf(os.Stderr, "ERROR go-log: %s: failed to set logging syslog backend", err)
78+
} else {
79+
lgbe = append(lgbe, slbe)
80+
}
81+
}
82+
83+
// logs written to stderr
84+
lgbe = append(lgbe, logging.NewLogBackend(colorable.NewColorableStderr(), "", 0))
85+
86+
// set the backend(s)
87+
logging.SetBackend(lgbe...)
5588
logging.SetFormatter(logging.MustStringFormatter(lfmt))
5689

5790
lvl := logging.ERROR

0 commit comments

Comments
 (0)