Logger fixes

This commit is contained in:
Kevin Cotugno 2017-09-10 10:57:35 -07:00
parent 62e2cc2a37
commit 1592631971
3 changed files with 86 additions and 68 deletions

View File

@ -1,5 +1,5 @@
package tacitus
type Logger interface {
Info(format string, ...interface{})
Info(format string, params ...interface{})
}

View File

@ -1,67 +0,0 @@
package io
import (
"fmt"
"os"
"time"
)
const tmpl = "%v - %v: "
type Logger struct {
DateFormat string
Path string
Stderr bool
UTC bool
file *os.File
}
func NewLogger() *Logger {
l := Logger{}
l.DateFormat = time.RFC3339Nano
l.Stderr = true
return &l
}
func (l *Logger) Start() error {
log, err := os.OpenFile(l.Path, os.O_APPEND | os.O_CREATE | os.O_WRONLY, 0640)
if err != nil {
return err
}
if l.file != nil {
l.file.Close()
}
l.file = log
log = true
}
func (l *Logger) Stop() {
log = false
l.file.Close()
}
func (l *Logger) Info(format string, params ...interface{}) {
format = tmpl + format
params = append([]interface{l.formattedTime, "I"}, params)
if l.Stderr {
fmt.Fprintf(os.Stderr, format, params)
}
if l.file != nil {
fmt.Fprintf(l.file, format, params)
}
}
func (l * Logger) formattedTime() string {
t := time.Now()
if l.UTC {
t = t.UTC()
return t.Format(l.DateFormat)
}

85
osutil/logger_service.go Normal file
View File

@ -0,0 +1,85 @@
package osutil
import (
"fmt"
"os"
"time"
"strings"
)
const tmpl = "%v - %v: "
type LoggerService struct {
DateFormat string
Path string
Stderr bool
Utc bool
file *os.File
log bool
}
func NewLogger() *LoggerService {
l := Logger{}
l.DateFormat = time.RFC3339Nano
l.Stderr = true
return &l
}
func (l *LoggerService) Start() error {
if l.Path != "" {
log, err := os.OpenFile(l.Path, os.O_APPEND | os.O_CREATE | os.O_WRONLY, 0640)
if err != nil {
return err
}
if l.file != nil {
l.file.Close()
}
l.file = log
}
l.log = true
return nil
}
func (l *LoggerService) Stop() {
l.log = false
if l.file != nil {
l.file.Close()
l.file = nil
}
}
func (l *LoggerService) Info(format string, params ...interface{}) {
format = tmpl + format
params = append([]interface{}{l.formattedTime(), "I"}, params...)
if l.Stderr {
fmt.Fprintf(os.Stderr, formatNewLine(format), params...)
}
if l.file != nil {
fmt.Fprintf(l.file, format, params)
}
}
func (l * Logger) formattedTime() string {
t := time.Now()
if l.Utc {
t = t.UTC()
}
return t.Format(l.DateFormat)
}
func formatNewLine(format string) string {
s := strings.Replace(format, "\n", " ", -1)
s = strings.TrimSpace(s)
return s + "\n"
}