File: xlogconfig.go

package info (click to toggle)
golang-github-hlandau-dexlogconfig 0.0~git20161112.0.244f29b-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch, stretch-backports
  • size: 84 kB
  • ctags: 27
  • sloc: makefile: 2
file content (76 lines) | stat: -rw-r--r-- 1,750 bytes parent folder | download | duplicates (3)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Package dexlogconfig is a policy package to configure xlog as I like it.
package dexlogconfig

import "github.com/hlandau/xlog"
import "gopkg.in/hlandau/easyconfig.v1/cflag"
import "os"
import _ "github.com/hlandau/buildinfo"
import "gopkg.in/hlandau/svcutils.v1/systemd"

var (
	flagGroup          = cflag.NewGroup(nil, "xlog")
	logSeverityFlag    = cflag.String(flagGroup, "severity", "NOTICE", "Log severity (any syslog severity name or number)")
	logFileFlag        = cflag.String(flagGroup, "file", "", "Log to filename")
	fileSeverityFlag   = cflag.String(flagGroup, "fileseverity", "TRACE", "File logging severity limit")
	logStderrFlag      = cflag.Bool(flagGroup, "stderr", true, "Log to stderr?")
	stderrSeverityFlag = cflag.String(flagGroup, "stderrseverity", "TRACE", "stderr logging severity limit")
)

func openStderr() {
	if logStderrFlag.Value() {
		if sev, ok := xlog.ParseSeverity(stderrSeverityFlag.Value()); ok {
			xlog.StderrSink.SetSeverity(sev)
		}

		if systemd.IsRunningUnder() {
			xlog.StderrSink.Systemd = true
		}

		return
	}

	xlog.RootSink.Remove(xlog.StderrSink)
}

func openFile() {
	fn := logFileFlag.Value()
	if fn == "" {
		return
	}

	f, err := os.Create(fn)
	if err != nil {
		return
	}

	sink := xlog.NewWriterSink(f)
	if sev, ok := xlog.ParseSeverity(fileSeverityFlag.Value()); ok {
		sink.SetSeverity(sev)
	}

	xlog.RootSink.Add(sink)
}

func setSeverity() {
	sevs := logSeverityFlag.Value()
	sev, ok := xlog.ParseSeverity(sevs)
	if !ok {
		return
	}

	xlog.Root.SetSeverity(sev)

	xlog.VisitSites(func(s xlog.Site) error {
		s.SetSeverity(sev)
		return nil
	})
}

// Parse registered configurables and setup logging.
func Init() {
	setSeverity()
	openStderr()
	openSyslog()
	openJournal()
	openFile()
}