File: logutil.go

package info (click to toggle)
elvish 0.21.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,372 kB
  • sloc: javascript: 236; sh: 130; python: 104; makefile: 88; xml: 9
file content (55 lines) | stat: -rw-r--r-- 1,314 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Package logutil provides logging utilities.
package logutil

import (
	"io"
	"log"
	"os"
)

var (
	out = io.Discard
	// If out is set by SetOutputFile, outFile is set and keeps the same value
	// as out. Otherwise, outFile is nil.
	outFile *os.File
	loggers []*log.Logger
)

// GetLogger gets a logger with a prefix.
func GetLogger(prefix string) *log.Logger {
	logger := log.New(out, prefix, log.LstdFlags)
	loggers = append(loggers, logger)
	return logger
}

// SetOutput redirects the output of all loggers obtained with GetLogger to the
// new io.Writer. If the old output was a file opened by SetOutputFile, it is
// closed.
func SetOutput(newout io.Writer) {
	if outFile != nil {
		outFile.Close()
		outFile = nil
	}
	out = newout
	for _, logger := range loggers {
		logger.SetOutput(out)
	}
}

// SetOutputFile redirects the output of all loggers obtained with GetLogger to
// the named file. If the old output was a file opened by SetOutputFile, it is
// closed. The new file is truncated. SetOutFile("") is equivalent to
// SetOutput(io.Discard).
func SetOutputFile(fname string) error {
	if fname == "" {
		SetOutput(io.Discard)
		return nil
	}
	file, err := os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		return err
	}
	SetOutput(file)
	outFile = file
	return nil
}