Add support for different log adapters

This commit is contained in:
Patrick Pacher 2020-09-24 10:57:43 +02:00
parent c479430d46
commit 1e8d2731dd
No known key found for this signature in database
GPG key ID: E8CD2DA160925A6D
3 changed files with 95 additions and 8 deletions

View file

@ -32,7 +32,6 @@ func (s Severity) String() string {
} }
func formatLine(line *logLine, duplicates uint64, useColor bool) string { func formatLine(line *logLine, duplicates uint64, useColor bool) string {
colorStart := "" colorStart := ""
colorEnd := "" colorEnd := ""
if useColor { if useColor {

View file

@ -33,6 +33,16 @@ import (
// Severity describes a log level. // Severity describes a log level.
type Severity uint32 type Severity uint32
// Message describes a log level message and is implemented
// by logLine.
type Message interface {
Text() string
Severity() Severity
Time() time.Time
File() string
LineNumber() int
}
type logLine struct { type logLine struct {
msg string msg string
tracer *ContextTracer tracer *ContextTracer
@ -42,6 +52,26 @@ type logLine struct {
line int line int
} }
func (ll *logLine) Text() string {
return ll.msg
}
func (ll *logLine) Severity() Severity {
return ll.level
}
func (ll *logLine) Time() time.Time {
return ll.timestamp
}
func (ll *logLine) File() string {
return ll.file
}
func (ll *logLine) LineNumber() int {
return ll.line
}
func (ll *logLine) Equal(ol *logLine) bool { func (ll *logLine) Equal(ol *logLine) bool {
switch { switch {
case ll.msg != ol.msg: case ll.msg != ol.msg:

View file

@ -7,11 +7,71 @@ import (
"time" "time"
) )
type (
// Adapter is used to write logs.
Adapter interface {
// Write is called for each log message.
Write(msg Message, duplicates uint64)
}
// AdapterFunc is a convenience type for implementing
// Adapter.
AdapterFunc func(msg Message, duplciates uint64)
// FormatFunc formats msg into a string.
FormatFunc func(msg Message, duplciates uint64) string
// SimpleFileAdapter implements Adapter and writes all
// messages to File.
SimpleFileAdapter struct {
Format FormatFunc
File *os.File
}
)
var ( var (
// StdoutAdapter is a simple file adapter that writes
// all logs to os.Stdout using a predefined format.
StdoutAdapter = &SimpleFileAdapter{
File: os.Stdout,
Format: defaultColorFormater,
}
// StderrAdapter is a simple file adapter that writes
// all logs to os.Stdout using a predefined format.
StderrAdapter = &SimpleFileAdapter{
File: os.Stderr,
Format: defaultColorFormater,
}
)
var (
adapter Adapter = StdoutAdapter
schedulingEnabled = false schedulingEnabled = false
writeTrigger = make(chan struct{}) writeTrigger = make(chan struct{})
) )
// SetAdapter configures the logging adapter to use.
// This must be called before the log package is initialized.
func SetAdapter(a Adapter) {
if initializing.IsSet() || a == nil {
return
}
adapter = a
}
// Write implements Adapter and calls fn.
func (fn AdapterFunc) Write(msg Message, duplicates uint64) {
fn(msg, duplicates)
}
// Write implements Adapter and writes msg the underlying file.
func (fileAdapter *SimpleFileAdapter) Write(msg Message, duplicates uint64) {
fmt.Fprintln(fileAdapter.File, fileAdapter.Format(msg, duplicates))
}
// EnableScheduling enables external scheduling of the logger. This will require to manually trigger writes via TriggerWrite whenevery logs should be written. Please note that full buffers will also trigger writing. Must be called before Start() to have an effect. // EnableScheduling enables external scheduling of the logger. This will require to manually trigger writes via TriggerWrite whenevery logs should be written. Please note that full buffers will also trigger writing. Must be called before Start() to have an effect.
func EnableScheduling() { func EnableScheduling() {
if !initializing.IsSet() { if !initializing.IsSet() {
@ -34,10 +94,8 @@ func TriggerWriterChannel() chan struct{} {
return writeTrigger return writeTrigger
} }
func writeLine(line *logLine, duplicates uint64) { func defaultColorFormater(line Message, duplicates uint64) string {
fmt.Println(formatLine(line, duplicates, true)) return formatLine(line.(*logLine), duplicates, true)
// TODO: implement file logging and setting console/file logging
// TODO: use https://github.com/natefinch/lumberjack
} }
func startWriter() { func startWriter() {
@ -132,7 +190,7 @@ StackTrace:
} }
// if currentLine and line are _not_ equal, output currentLine // if currentLine and line are _not_ equal, output currentLine
writeLine(currentLine, duplicates) adapter.Write(currentLine, duplicates)
// reset duplicate counter // reset duplicate counter
duplicates = 0 duplicates = 0
// set new currentLine // set new currentLine
@ -144,7 +202,7 @@ StackTrace:
// write final line // write final line
if currentLine != nil { if currentLine != nil {
writeLine(currentLine, duplicates) adapter.Write(currentLine, duplicates)
} }
// reset state // reset state
currentLine = nil //nolint:ineffassign currentLine = nil //nolint:ineffassign
@ -166,7 +224,7 @@ func finalizeWriting() {
for { for {
select { select {
case line := <-logBuffer: case line := <-logBuffer:
writeLine(line, 0) adapter.Write(line, 0)
case <-time.After(10 * time.Millisecond): case <-time.After(10 * time.Millisecond):
fmt.Printf("%s%s %s EOF%s\n", InfoLevel.color(), time.Now().Format(timeFormat), leftArrow, endColor()) fmt.Printf("%s%s %s EOF%s\n", InfoLevel.color(), time.Now().Format(timeFormat), leftArrow, endColor())
return return