blob: 1b3eaa59b4db5c4c0cfc451aee42f1c609136e42 [file] [log] [blame]
David K. Bainbridge528b3182017-01-23 08:51:59 -08001// Copyright 2016 Canonical Ltd.
2// Licensed under the LGPLv3, see LICENCE file for details.
3
4package loggo
5
6import (
7 "fmt"
8 "sort"
9 "strings"
10)
11
12// Config is a mapping of logger module names to logging severity levels.
13type Config map[string]Level
14
15// String returns a logger configuration string that may be parsed
16// using ParseConfigurationString.
17func (c Config) String() string {
18 if c == nil {
19 return ""
20 }
21 // output in alphabetical order.
22 names := []string{}
23 for name := range c {
24 names = append(names, name)
25 }
26 sort.Strings(names)
27
28 var entries []string
29 for _, name := range names {
30 level := c[name]
31 if name == "" {
32 name = rootString
33 }
34 entry := fmt.Sprintf("%s=%s", name, level)
35 entries = append(entries, entry)
36 }
37 return strings.Join(entries, ";")
38}
39
40func parseConfigValue(value string) (string, Level, error) {
41 pair := strings.SplitN(value, "=", 2)
42 if len(pair) < 2 {
43 return "", UNSPECIFIED, fmt.Errorf("config value expected '=', found %q", value)
44 }
45 name := strings.TrimSpace(pair[0])
46 if name == "" {
47 return "", UNSPECIFIED, fmt.Errorf("config value %q has missing module name", value)
48 }
49
50 levelStr := strings.TrimSpace(pair[1])
51 level, ok := ParseLevel(levelStr)
52 if !ok {
53 return "", UNSPECIFIED, fmt.Errorf("unknown severity level %q", levelStr)
54 }
55 if name == rootString {
56 name = ""
57 }
58 return name, level, nil
59}
60
61// ParseConfigString parses a logger configuration string into a map of logger
62// names and their associated log level. This method is provided to allow
63// other programs to pre-validate a configuration string rather than just
64// calling ConfigureLoggers.
65//
66// Logging modules are colon- or semicolon-separated; each module is specified
67// as <modulename>=<level>. White space outside of module names and levels is
68// ignored. The root module is specified with the name "<root>".
69//
70// As a special case, a log level may be specified on its own.
71// This is equivalent to specifying the level of the root module,
72// so "DEBUG" is equivalent to `<root>=DEBUG`
73//
74// An example specification:
75// `<root>=ERROR; foo.bar=WARNING`
76func ParseConfigString(specification string) (Config, error) {
77 specification = strings.TrimSpace(specification)
78 if specification == "" {
79 return nil, nil
80 }
81 cfg := make(Config)
82 if level, ok := ParseLevel(specification); ok {
83 cfg[""] = level
84 return cfg, nil
85 }
86
87 values := strings.FieldsFunc(specification, func(r rune) bool { return r == ';' || r == ':' })
88 for _, value := range values {
89 name, level, err := parseConfigValue(value)
90 if err != nil {
91 return nil, err
92 }
93 cfg[name] = level
94 }
95 return cfg, nil
96}