File: writer.go

package info (click to toggle)
golang-github-juju-loggo 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 260 kB
  • sloc: makefile: 10
file content (70 lines) | stat: -rw-r--r-- 1,790 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2014 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.

package loggo

import (
	"fmt"
	"io"
	"os"
)

// DefaultWriterName is the name of the default writer for
// a Context.
const DefaultWriterName = "default"

// Writer is implemented by any recipient of log messages.
type Writer interface {
	// Write writes a message to the Writer with the given level and module
	// name. The filename and line hold the file name and line number of the
	// code that is generating the log message; the time stamp holds the time
	// the log message was generated, and message holds the log message
	// itself.
	Write(entry Entry)
}

// NewMinLevelWriter returns a Writer that will only pass on the Write calls
// to the provided writer if the log level is at or above the specified
// minimum level.
func NewMinimumLevelWriter(writer Writer, minLevel Level) Writer {
	return &minLevelWriter{
		writer: writer,
		level:  minLevel,
	}
}

type minLevelWriter struct {
	writer Writer
	level  Level
}

// Write writes the log record.
func (w minLevelWriter) Write(entry Entry) {
	if entry.Level < w.level {
		return
	}
	w.writer.Write(entry)
}

type simpleWriter struct {
	writer    io.Writer
	formatter func(entry Entry) string
}

// NewSimpleWriter returns a new writer that writes log messages to the given
// io.Writer formatting the messages with the given formatter.
func NewSimpleWriter(writer io.Writer, formatter func(entry Entry) string) Writer {
	if formatter == nil {
		formatter = DefaultFormatter
	}
	return &simpleWriter{writer, formatter}
}

func (simple *simpleWriter) Write(entry Entry) {
	logLine := simple.formatter(entry)
	fmt.Fprintln(simple.writer, logLine)
}

func defaultWriter() Writer {
	return NewSimpleWriter(os.Stderr, DefaultFormatter)
}