all repos — honk @ 4124f790bbcde57cc9b17f2899b14f1e2446563d

my fork of honk

log.go (view raw)

 1//
 2// Copyright (c) 2022 Ted Unangst <tedu@tedunangst.com>
 3//
 4// Permission to use, copy, modify, and distribute this software for any
 5// purpose with or without fee is hereby granted, provided that the above
 6// copyright notice and this permission notice appear in all copies.
 7//
 8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
16package main
17
18import (
19	"flag"
20	"io/ioutil"
21	"log"
22	"log/syslog"
23	"os"
24)
25
26var elog = log.Default()
27var ilog = log.Default()
28var dlog = log.Default()
29
30var elogname, ilogname, dlogname, alllogname string
31
32func init() {
33	flag.StringVar(&elogname, "errorlog", "stderr", "error log file (or stderr, null, syslog)")
34	flag.StringVar(&ilogname, "infolog", "stderr", "info log file (or stderr, null, syslog)")
35	flag.StringVar(&dlogname, "debuglog", "stderr", "debug log file (or stderr, null, syslog)")
36	flag.StringVar(&alllogname, "log", "stderr", "combined log file (or stderr, null, syslog)")
37
38}
39
40func initLogging(elogname, ilogname, dlogname string) {
41	elog = openlog(elogname, syslog.LOG_ERR)
42	ilog = openlog(ilogname, syslog.LOG_INFO)
43	dlog = openlog(dlogname, syslog.LOG_DEBUG)
44}
45
46func openlog(name string, prio syslog.Priority) *log.Logger {
47	if name == "stderr" {
48		return log.Default()
49	}
50	if name == "stdout" {
51		return log.New(os.Stdout, os.Args[0], log.LstdFlags)
52	}
53	if name == "null" {
54		return log.New(ioutil.Discard, os.Args[0], log.LstdFlags)
55	}
56	if name == "syslog" {
57		logger, err := syslog.NewLogger(syslog.LOG_UUCP|prio, 0)
58		if err != nil {
59			elog.Printf("can't create syslog: %s", err)
60			return log.Default()
61		}
62		return logger
63	}
64	fd, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
65	if err != nil {
66		elog.Printf("can't open log file %s: %s", name, err)
67		return log.Default()
68	}
69	logger := log.New(fd, os.Args[0], log.LstdFlags)
70	logger.Printf("new log started")
71	return logger
72}