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 == "syslog" {
51 logger, err := syslog.NewLogger(syslog.LOG_UUCP|prio, 0)
52 if err != nil {
53 elog.Printf("can't create syslog: %s", err)
54 return log.Default()
55 }
56 return logger
57 }
58 if name == "null" {
59 return log.New(ioutil.Discard, os.Args[0], log.LstdFlags)
60 }
61 fd, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
62 if err != nil {
63 elog.Printf("can't open log file %s: %s", name, err)
64 return log.Default()
65 }
66 logger := log.New(fd, os.Args[0], log.LstdFlags)
67 logger.Printf("new log started")
68 return logger
69}