all repos — honk @ 1cdcf0570ab2ce9ec07863dd7670d1e7e42173e4

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
26// log.Default() not added until go 1.16
27func logdefault() *log.Logger {
28	return log.New(os.Stderr, "", log.LstdFlags)
29}
30
31var elog = logdefault()
32var ilog = logdefault()
33var dlog = logdefault()
34
35var elogname, ilogname, dlogname, alllogname string
36
37func init() {
38	flag.StringVar(&elogname, "errorlog", "stderr", "error log file (or stderr, null, syslog)")
39	flag.StringVar(&ilogname, "infolog", "stderr", "info log file (or stderr, null, syslog)")
40	flag.StringVar(&dlogname, "debuglog", "stderr", "debug log file (or stderr, null, syslog)")
41	flag.StringVar(&alllogname, "log", "stderr", "combined log file (or stderr, null, syslog)")
42
43}
44
45func loggingArgs() []string {
46	return []string{"-errorlog", elogname, "-infolog", ilogname, "-debuglog", dlogname}
47}
48
49func initLogging(elogname, ilogname, dlogname string) {
50	elog = openlog(elogname, syslog.LOG_ERR)
51	ilog = openlog(ilogname, syslog.LOG_INFO)
52	dlog = openlog(dlogname, syslog.LOG_DEBUG)
53}
54
55func openlog(name string, prio syslog.Priority) *log.Logger {
56	if name == "stderr" {
57		return log.New(os.Stderr, "", log.LstdFlags)
58	}
59	if name == "stdout" {
60		return log.New(os.Stdout, "", log.LstdFlags)
61	}
62	if name == "null" {
63		return log.New(ioutil.Discard, "", log.LstdFlags)
64	}
65	if name == "syslog" {
66		w, err := syslog.New(syslog.LOG_UUCP|prio, "honk")
67		if err != nil {
68			elog.Printf("can't create syslog: %s", err)
69			return logdefault()
70		}
71		return log.New(w, "", log.LstdFlags)
72	}
73	fd, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
74	if err != nil {
75		elog.Printf("can't open log file %s: %s", name, err)
76		return logdefault()
77	}
78	logger := log.New(fd, "", log.LstdFlags)
79	logger.Printf("new log started")
80	return logger
81}