all repos — honk @ a11d178e7eada243d3aa82192595216d4b20e88c

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, os.Args[0], 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 initLogging(elogname, ilogname, dlogname string) {
46	elog = openlog(elogname, syslog.LOG_ERR)
47	ilog = openlog(ilogname, syslog.LOG_INFO)
48	dlog = openlog(dlogname, syslog.LOG_DEBUG)
49}
50
51func openlog(name string, prio syslog.Priority) *log.Logger {
52	if name == "stderr" {
53		return log.New(os.Stderr, os.Args[0], log.LstdFlags)
54	}
55	if name == "stdout" {
56		return log.New(os.Stdout, os.Args[0], log.LstdFlags)
57	}
58	if name == "null" {
59		return log.New(ioutil.Discard, os.Args[0], log.LstdFlags)
60	}
61	if name == "syslog" {
62		logger, err := syslog.NewLogger(syslog.LOG_UUCP|prio, 0)
63		if err != nil {
64			elog.Printf("can't create syslog: %s", err)
65			return logdefault()
66		}
67		return logger
68	}
69	fd, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
70	if err != nil {
71		elog.Printf("can't open log file %s: %s", name, err)
72		return logdefault()
73	}
74	logger := log.New(fd, os.Args[0], log.LstdFlags)
75	logger.Printf("new log started")
76	return logger
77}