1 // 2 // Copyright (c) SAS Institute Inc. 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 // 16 17 package isologger 18 19 import ( 20 "io" 21 "log" 22 "strings" 23 "time" 24 ) 25 26 const RFC3339Milli = "2006-01-02T15:04:05.000Z07:00" // RFC3339 with 3 decimal places, padded 27 28 type isoLogger struct { 29 io.Writer 30 format string 31 } 32 33 // Configure the logger to emit formatted timestamps to the given writer. The 34 // format string must always produce output that is no longer than the format 35 // string itself, otherwise behavior is undefined. If logger is nil, then the 36 // default logger is updated. 37 func SetOutput(logger *log.Logger, w io.Writer, format string) { 38 // make the prefix big enough to hold the timestamp 39 prefix := strings.Repeat(" ", len(format)+1) 40 output := isoLogger{Writer: w, format: format} 41 if logger == nil { 42 log.SetFlags(0) 43 log.SetPrefix(prefix) 44 log.SetOutput(output) 45 } else { 46 logger.SetFlags(0) 47 logger.SetPrefix(prefix) 48 logger.SetOutput(output) 49 } 50 } 51 52 func (i isoLogger) Write(d []byte) (int, error) { 53 // scribble timestamp over the prefix. this is violating the Writer 54 // contract but only logger is going to call this anyway. 55 ts := time.Now().Format(i.format) 56 copy(d, ts) 57 // shift everything left if the formatted string was shorter 58 if len(ts) != len(i.format) { 59 d = append(d[:len(ts)], d[len(i.format):]...) 60 } 61 return i.Writer.Write(d) 62 } 63