blob: db7e82ad7ef46fc8c65cfe47a69a7738774ef0fc [file] [log] [blame]
Dan Willemsen1e704462016-08-21 15:17:17 -07001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Package logger implements a logging package designed for command line
16// utilities. It uses the standard 'log' package and function, but splits
17// output between stderr and a rotating log file.
18//
19// In addition to the standard logger functions, Verbose[f|ln] calls only go to
20// the log file by default, unless SetVerbose(true) has been called.
21//
22// The log file also includes extended date/time/source information, which are
23// omitted from the stderr output for better readability.
24//
25// In order to better handle resource cleanup after a Fatal error, the Fatal
26// functions panic instead of calling os.Exit(). To actually do the cleanup,
27// and prevent the printing of the panic, call defer logger.Cleanup() at the
28// beginning of your main function.
29package logger
30
31import (
32 "errors"
33 "fmt"
34 "io"
35 "io/ioutil"
36 "log"
37 "os"
38 "path/filepath"
39 "strconv"
40 "sync"
41)
42
43type Logger interface {
44 // Print* prints to both stderr and the file log.
45 // Arguments to Print are handled in the manner of fmt.Print.
46 Print(v ...interface{})
47 // Arguments to Printf are handled in the manner of fmt.Printf
48 Printf(format string, v ...interface{})
49 // Arguments to Println are handled in the manner of fmt.Println
50 Println(v ...interface{})
51
52 // Verbose* is equivalent to Print*, but skips stderr unless the
53 // logger has been configured in verbose mode.
54 Verbose(v ...interface{})
55 Verbosef(format string, v ...interface{})
56 Verboseln(v ...interface{})
57
58 // Fatal* is equivalent to Print* followed by a call to panic that
59 // can be converted to an error using Recover, or will be converted
60 // to a call to os.Exit(1) with a deferred call to Cleanup()
61 Fatal(v ...interface{})
62 Fatalf(format string, v ...interface{})
63 Fatalln(v ...interface{})
64
65 // Panic is equivalent to Print* followed by a call to panic.
66 Panic(v ...interface{})
67 Panicf(format string, v ...interface{})
68 Panicln(v ...interface{})
69
70 // Output writes the string to both stderr and the file log.
71 Output(calldepth int, str string) error
72}
73
74// fatalLog is the type used when Fatal[f|ln]
75type fatalLog error
76
77func fileRotation(from, baseName, ext string, cur, max int) error {
78 newName := baseName + "." + strconv.Itoa(cur) + ext
79
80 if _, err := os.Lstat(newName); err == nil {
81 if cur+1 <= max {
82 fileRotation(newName, baseName, ext, cur+1, max)
83 }
84 }
85
86 if err := os.Rename(from, newName); err != nil {
87 return fmt.Errorf("Failed to rotate", from, "to", newName, ".", err)
88 }
89 return nil
90}
91
92// CreateFileWithRotation returns a new os.File using os.Create, renaming any
93// existing files to <filename>.#.<ext>, keeping up to maxCount files.
94// <filename>.1.<ext> is the most recent backup, <filename>.2.<ext> is the
95// second most recent backup, etc.
96//
97// TODO: This function is not guaranteed to be atomic, if there are multiple
98// users attempting to do the same operation, the result is undefined.
99func CreateFileWithRotation(filename string, maxCount int) (*os.File, error) {
100 if _, err := os.Lstat(filename); err == nil {
101 ext := filepath.Ext(filename)
102 basename := filename[:len(filename)-len(ext)]
103 if err = fileRotation(filename, basename, ext, 1, maxCount); err != nil {
104 return nil, err
105 }
106 }
107
108 return os.Create(filename)
109}
110
111// Recover can be used with defer in a GoRoutine to convert a Fatal panics to
112// an error that can be handled.
113func Recover(fn func(err error)) {
114 p := recover()
115
116 if p == nil {
117 return
118 } else if log, ok := p.(fatalLog); ok {
119 fn(error(log))
120 } else {
121 panic(p)
122 }
123}
124
125type stdLogger struct {
126 stderr *log.Logger
127 verbose bool
128
129 fileLogger *log.Logger
130 mutex sync.Mutex
131 file *os.File
132}
133
134var _ Logger = &stdLogger{}
135
136// New creates a new Logger. The out variable sets the destination, commonly
137// os.Stderr, but it may be a buffer for tests, or a separate log file if
138// the user doesn't need to see the output.
139func New(out io.Writer) *stdLogger {
140 return &stdLogger{
141 stderr: log.New(out, "", log.Ltime),
142 fileLogger: log.New(ioutil.Discard, "", log.Ldate|log.Lmicroseconds|log.Llongfile),
143 }
144}
145
146// SetVerbose controls whether Verbose[f|ln] logs to stderr as well as the
147// file-backed log.
148func (s *stdLogger) SetVerbose(v bool) {
149 s.verbose = v
150}
151
152// SetOutput controls where the file-backed log will be saved. It will keep
153// some number of backups of old log files.
154func (s *stdLogger) SetOutput(path string) {
155 if f, err := CreateFileWithRotation(path, 5); err == nil {
156 s.mutex.Lock()
157 defer s.mutex.Unlock()
158
159 if s.file != nil {
160 s.file.Close()
161 }
162 s.file = f
163 s.fileLogger.SetOutput(f)
164 } else {
165 s.Fatal(err.Error())
166 }
167}
168
169// Close disables logging to the file and closes the file handle.
170func (s *stdLogger) Close() {
171 s.mutex.Lock()
172 defer s.mutex.Unlock()
173 if s.file != nil {
174 s.fileLogger.SetOutput(ioutil.Discard)
175 s.file.Close()
176 s.file = nil
177 }
178}
179
180// Cleanup should be used with defer in your main function. It will close the
181// log file and convert any Fatal panics back to os.Exit(1)
182func (s *stdLogger) Cleanup() {
183 fatal := false
184 p := recover()
185
186 if _, ok := p.(fatalLog); ok {
187 fatal = true
188 p = nil
189 } else if p != nil {
190 s.Println(p)
191 }
192
193 s.Close()
194
195 if p != nil {
196 panic(p)
197 } else if fatal {
198 os.Exit(1)
199 }
200}
201
202// Output writes string to both stderr and the file log.
203func (s *stdLogger) Output(calldepth int, str string) error {
204 s.stderr.Output(calldepth+1, str)
205 return s.fileLogger.Output(calldepth+1, str)
206}
207
208// VerboseOutput is equivalent to Output, but only goes to the file log
209// unless SetVerbose(true) has been called.
210func (s *stdLogger) VerboseOutput(calldepth int, str string) error {
211 if s.verbose {
212 s.stderr.Output(calldepth+1, str)
213 }
214 return s.fileLogger.Output(calldepth+1, str)
215}
216
217// Print prints to both stderr and the file log.
218// Arguments are handled in the manner of fmt.Print.
219func (s *stdLogger) Print(v ...interface{}) {
220 output := fmt.Sprint(v...)
221 s.Output(2, output)
222}
223
224// Printf prints to both stderr and the file log.
225// Arguments are handled in the manner of fmt.Printf.
226func (s *stdLogger) Printf(format string, v ...interface{}) {
227 output := fmt.Sprintf(format, v...)
228 s.Output(2, output)
229}
230
231// Println prints to both stderr and the file log.
232// Arguments are handled in the manner of fmt.Println.
233func (s *stdLogger) Println(v ...interface{}) {
234 output := fmt.Sprintln(v...)
235 s.Output(2, output)
236}
237
238// Verbose is equivalent to Print, but only goes to the file log unless
239// SetVerbose(true) has been called.
240func (s *stdLogger) Verbose(v ...interface{}) {
241 output := fmt.Sprint(v...)
242 s.VerboseOutput(2, output)
243}
244
245// Verbosef is equivalent to Printf, but only goes to the file log unless
246// SetVerbose(true) has been called.
247func (s *stdLogger) Verbosef(format string, v ...interface{}) {
248 output := fmt.Sprintf(format, v...)
249 s.VerboseOutput(2, output)
250}
251
252// Verboseln is equivalent to Println, but only goes to the file log unless
253// SetVerbose(true) has been called.
254func (s *stdLogger) Verboseln(v ...interface{}) {
255 output := fmt.Sprintln(v...)
256 s.VerboseOutput(2, output)
257}
258
259// Fatal is equivalent to Print() followed by a call to panic() that
260// Cleanup will convert to a os.Exit(1).
261func (s *stdLogger) Fatal(v ...interface{}) {
262 output := fmt.Sprint(v...)
263 s.Output(2, output)
264 panic(fatalLog(errors.New(output)))
265}
266
267// Fatalf is equivalent to Printf() followed by a call to panic() that
268// Cleanup will convert to a os.Exit(1).
269func (s *stdLogger) Fatalf(format string, v ...interface{}) {
270 output := fmt.Sprintf(format, v...)
271 s.Output(2, output)
272 panic(fatalLog(errors.New(output)))
273}
274
275// Fatalln is equivalent to Println() followed by a call to panic() that
276// Cleanup will convert to a os.Exit(1).
277func (s *stdLogger) Fatalln(v ...interface{}) {
278 output := fmt.Sprintln(v...)
279 s.Output(2, output)
280 panic(fatalLog(errors.New(output)))
281}
282
283// Panic is equivalent to Print() followed by a call to panic().
284func (s *stdLogger) Panic(v ...interface{}) {
285 output := fmt.Sprint(v...)
286 s.Output(2, output)
287 panic(output)
288}
289
290// Panicf is equivalent to Printf() followed by a call to panic().
291func (s *stdLogger) Panicf(format string, v ...interface{}) {
292 output := fmt.Sprintf(format, v...)
293 s.Output(2, output)
294 panic(output)
295}
296
297// Panicln is equivalent to Println() followed by a call to panic().
298func (s *stdLogger) Panicln(v ...interface{}) {
299 output := fmt.Sprintln(v...)
300 s.Output(2, output)
301 panic(output)
302}