]> www.average.org Git - loctrkd.git/blob - gps303/common.py
Beautify logging
[loctrkd.git] / gps303 / common.py
1 """ Common housekeeping for all daemons """
2
3 from configparser import ConfigParser
4 from getopt import getopt
5 from logging import Formatter, getLogger, StreamHandler, DEBUG, INFO
6 from logging.handlers import SysLogHandler
7 from pkg_resources import get_distribution, DistributionNotFound
8 from sys import argv, stderr, stdout
9
10 CONF = "/etc/gps303.conf"
11 PORT = 4303
12 DBFN = "/var/lib/gps303/gps303.sqlite"
13
14 try:
15     version = get_distribution("gps303").version
16 except DistributionNotFound:
17     version = "<local>"
18
19
20 def init(log, opts=None):
21     if opts is None:
22         opts, _ = getopt(argv[1:], "c:d")
23     opts = dict(opts)
24     conf = readconfig(opts["-c"] if "-c" in opts else CONF)
25     if stdout.isatty():
26         hdl = StreamHandler(stderr)
27         hdl.setFormatter(
28             Formatter("%(asctime)s - %(levelname)s - %(message)s")
29         )
30         log.addHandler(hdl)
31     else:
32         hdl = SysLogHandler(address="/dev/log")
33         hdl.setFormatter(
34             Formatter("%(name)s[%(process)d]: %(levelname)s - %(message)s")
35         )
36         log.addHandler(hdl)
37     log.setLevel(DEBUG if "-d" in opts else INFO)
38     log.info("%s starting with options: %s", version, opts)
39     return conf
40
41
42 def readconfig(fname):
43     config = ConfigParser()
44     config["collector"] = {
45         "port": PORT,
46     }
47     config["storage"] = {
48         "dbfn": DBFN,
49     }
50     config["termconfig"] = {}
51     config.read(fname)
52     return config
53
54
55 def normconf(section):
56     result = {}
57     for key, val in section.items():
58         vals = val.split("\n")
59         if len(vals) > 1 and vals[0] == "":
60             vals = vals[1:]
61         lst = []
62         for el in vals:
63             try:
64                 el = int(el, 0)
65             except ValueError:
66                 if el[0] == '"' and el[-1] == '"':
67                     el = el.strip('"').rstrip('"')
68             lst.append(el)
69         if len(lst) == 1:
70             [lst] = lst
71         result[key] = lst
72     return result
73
74
75 if __name__ == "__main__":
76     from sys import argv
77
78     def _print_config(conf):
79         for section in conf.sections():
80             print("section", section)
81             for option in conf.options(section):
82                 print("    ", option, conf[section][option])
83
84     conf = readconfig(argv[1])
85     _print_config(conf)
86     print(normconf(conf["termconfig"]))