klog

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 23, 2019 License: Apache-2.0 Imports: 16 Imported by: 0

README

klog Build Status GoDoc License

Package klog provides an simple, flexible, extensible, powerful and structured logging tool based on the level, which has done the better balance between the flexibility and the performance. It is inspired by log15, logrus, go-kit, logger and log.

See the GoDoc.

API has been stable. The current is v1.x.

Prerequisite

Now klog requires Go 1.x.

Features

  • The better performance.
  • Lazy evaluation of expensive operations.
  • Simple, Flexible, Extensible, Powerful and Structured.
  • Child loggers which inherit and add their own private context.
  • Built-in support for logging to files, syslog, and the network. See Writer.

Example

package main

import "github.com/xgfone/klog"

func main() {
	log := klog.New().WithLevel(klog.LvlWarn).WithKv("key1", "value1")

	field1 := klog.Field{Key: "key2", Value: "value2"}
	field2 := klog.Field{Key: "key3", Value: "value3"}
	log.Info().K("key4", "value4").Print("don't output")
	log.Error(field1, field2).K("key4", "value4").Printf("will output %s", "placeholder")

	// Output:
	// t=2019-05-23T10:36:06.8399426+08:00 lvl=ERROR key1=value1 key2=value2 key3=value3 key4=value4 msg=will output placeholder
}

Furthermore, klog has built in a global logger, Std, which is equal to klog.New(), and you can use it and its exported function, Trace(), Debug, Info, Warn, Error, Panic, Fatal, or L(level). Suggestion: You should use these functions instead.

package main

import "github.com/xgfone/klog"

func main() {
	klog.Std = klog.Std.WithLevel(klog.LvlWarn)

	klog.Info().K("key", "value").Msg("don't output")
	klog.Error().K("key", "value").Msgf("will output %s", "placeholder")

	// Output:
	// t=2019-05-22T16:05:56.2318273+08:00 lvl=ERROR key=value msg=will output placeholder
}
Inherit the context of the parent logger
package main

import "github.com/xgfone/klog"

func main() {
	parent := klog.New().WithKv("parent", 123)
	child := parent.WithKv("child", 456)
	child.Info().Msgf("hello %s", "world")

	// Output:
	// t=2019-05-22T16:14:56.3740242+08:00 lvl=INFO parent=123 child=456 msg=hello world
}
Encoder
type Encoder func(buf *Builder, r Record) error

This pakcage has implemented four kinds of encoders, NothingEncoder, TextEncoder, JSONEncoder and StdJSONEncoder. It will use TextEncoder by default, but you can set it to others.

package main

import "github.com/xgfone/klog"

func main() {
	log := klog.New().WithEncoder(klog.JSONEncoder())
	log.Info().K("key1", "value1").K("key2", "value2").Msg("hello world")

	// Output:
	// {"t":"2019-05-22T16:19:03.2972646+08:00","lvl":"INFO","key1":"value1","key2":"value2","msg":"hello world"}
}
Writer
type Writer interface {
	io.Closer
	Write(level Level, data []byte) (n int, err error)
}

All implementing the interface Writer are a Writer.

There are some built-in writers, such as DiscardWriter, LevelWriter, SafeWriter, StreamWriter, MultiWriter, FailoverWriter, ReopenWriter, NetWriter, SyslogWriter andSyslogNetWriter. It also supplies a rotating-size file writer SizedRotatingFile.

package main

import (
	"fmt"

	"github.com/xgfone/klog"
)

func main() {
	file, err := klog.NewSizedRotatingFile("test.log", 1024*1024*100, 100)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()

	log := klog.New(klog.StreamWriter(file))
	log.Info().K("key", "value").Msg("hello world")

	// Output to file test.log:
	// t=2019-05-22T16:34:09.0685161+08:00 lvl=INFO key=value msg=hello world
}

If you want to use SizedRotatingFile as the writer, NewSimpleLogger maybe is your better choice.

package main

import "github.com/xgfone/klog"

func main() {
	log, _ := klog.NewSimpleLogger("warn", "test.log", "100M", 100)

	log.Info().Print("don't output")
	log.Error().Printf("will output %s %s", "key", "value")

	// Output to test.log:
	// t=2019-05-23T17:20:45.0741975+08:00 lvl=ERROR msg=will output key value
}
Lazy evaluation
type Valuer func(Record) (v interface{})

If the type of a certain value is Valuer, the logger engine will call it to get the corresponding value firstly before calling the encoder. There are some built-in Valuer, such as Caller(), CallerStack(), LineNo(), LineNoAsInt(), FuncName(), FuncFullName(), FileName(), FileLongName() and Package().

package main

import "github.com/xgfone/klog"

func main() {
	log := klog.Std.WithKv("caller", klog.Caller())
	log.Info().K("stack", klog.CallerStack()).Msg("hello world")

	// Output:
	// t=2019-05-22T16:41:03.1281272+08:00 lvl=INFO caller=main.go:9 stack=[main.go:9] msg=hello world
}
Hook
type Hook func(name string, level Level) bool

You can use the hook to filter or count logs. There are four built-in hooks, DisableLogger, EnableLogger, DisableLoggerFromEnv and EnableLoggerFromEnv.

package main

import "github.com/xgfone/klog"

func main() {
	klog.Std = klog.Std.WithHook(klog.EnableLoggerFromEnv("mod"))

	log := klog.Std.WithName("debug")
	log.Info().Msg("hello world")

	// $ go run main.go  # No output
	// $ mod=debug=1 go run main.go
	// t=2019-05-22T17:07:20.2504266+08:00 logger=debug lvl=INFO msg=hello world
}

Performance

The log framework itself has no any performance costs and the key of the bottleneck is the encoder.

test ops ns/op bytes/op allocs/op
BenchmarkKlogNothingEncoder-4 10000000 149 ns/op 32 B/op 1 allocs/op
BenchmarkKlogTextEncoder-4 5000000 281 ns/op 32 B/op 1 allocs/op
BenchmarkKlogJSONEncoder-4 5000000 313 ns/op 32 B/op 1 allocs/op
BenchmarkKlogStdJSONEncoder-4 1000000 1043 ns/op 1455 B/op 22 allocs/op

Notice: The once memory allocation, 32 B/op and 1 allocs/op, is due to the slice type []Field.

Documentation

Overview

Package klog provides an simple, flexible, extensible, powerful and structured logging tool based on the level, which has done the better balance between the flexibility and the performance.

Features

  • The better performance.
  • Lazy evaluation of expensive operations.
  • Simple, Flexible, Extensible, Powerful and Structured.
  • Child loggers which inherit and add their own private context.
  • Built-in support for logging to files, syslog, and the network. See `Writer`.

Index

Examples

Constants

This section is empty.

Variables

View Source
var Levels = map[Level]string{
	LvlTrace: "TRACE",
	LvlDebug: "DEBUG",
	LvlInfo:  "INFO",
	LvlWarn:  "WARN",
	LvlError: "ERROR",
	LvlPanic: "PANIC",
	LvlFatal: "FATAL",
}

Levels is the pre-defined level names, but you can reset and override them.

View Source
var Std = New()

Std is the global default Logger.

Functions

func AppendCleaner

func AppendCleaner(clean ...func())

AppendCleaner appends the clean functions, which will be called when emitting the FATAL log.

func FromWriter

func FromWriter(w Writer) io.WriteCloser

FromWriter converts Writer to io.WriteCloser.

func ParseSize

func ParseSize(s string) (size int64, err error)

ParseSize parses the size string. The size maybe have a unit suffix, such as "123", "123M, 123G". Valid size units are "b", "B", "k", "K", "m", "M", "g", "G", "t", "T", "p", "P". The lower units are 1000x, and the upper units are 1024x.

Notice: "" will be considered as 0.

Example
m10, _ := ParseSize("100M")
g10, _ := ParseSize("10g")

fmt.Println(m10)
fmt.Println(g10)
Output:
104857600
10000000000

Types

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder is a thin wrapper around a byte slice. It's intended to be pooled, so the only way to construct one is via a Pool.

func NewBuilder

func NewBuilder(n int) *Builder

NewBuilder returns a new Builder with a initial capacity n.

func NewBuilderBytes

func NewBuilderBytes(buf []byte) *Builder

NewBuilderBytes returns a new Builder with a initial data.

func NewBuilderString

func NewBuilderString(s string) *Builder

NewBuilderString returns a new Builder with a initial string.

func (*Builder) AppendAny

func (b *Builder) AppendAny(any interface{}) (ok bool, err error)

AppendAny appends any value to the underlying buffer.

It supports the type:

nil     ==> "<nil>"
bool    ==> "true" or "false"
[]byte
string
float32
float64
int
int8
int16
int32
int64
uint
uint8
uint16
uint32
uint64
time.Time ==> time.RFC3339Nano
interface error
interface fmt.Stringer
interface encoding.TextMarshaler

For the unknown type, it does not append it and return false, or return true.

func (*Builder) AppendBool

func (b *Builder) AppendBool(v bool)

AppendBool appends a bool to the underlying buffer.

func (*Builder) AppendByte

func (b *Builder) AppendByte(c byte)

AppendByte is the same as WriteByte, but no return.

func (*Builder) AppendFloat

func (b *Builder) AppendFloat(f float64, bitSize int)

AppendFloat appends a float to the underlying buffer. It doesn't quote NaN or +/- Inf.

func (*Builder) AppendInt

func (b *Builder) AppendInt(i int64)

AppendInt appends an integer to the underlying buffer (assuming base 10).

func (*Builder) AppendJSON

func (b *Builder) AppendJSON(value interface{}) error

AppendJSON appends the value as the JSON value, that's, the value will be encoded to JSON and appended into the underlying byte slice.

func (*Builder) AppendJSONString

func (b *Builder) AppendJSONString(s string)

AppendJSONString appends a string as JSON string, which will escape the double quotation(") and enclose it with a pair of the double quotation.

func (*Builder) AppendString

func (b *Builder) AppendString(s string)

AppendString is the same as WriteString, but no return.

func (*Builder) AppendTime

func (b *Builder) AppendTime(t time.Time, layout string)

AppendTime appends a time to the underlying buffer.

func (*Builder) AppendUint

func (b *Builder) AppendUint(i uint64)

AppendUint appends an unsigned integer to the underlying buffer (assuming base 10).

func (*Builder) Bytes

func (b *Builder) Bytes() []byte

Bytes returns a mutable reference to the underlying byte slice.

func (*Builder) Cap

func (b *Builder) Cap() int

Cap returns the capacity of the underlying byte slice.

func (*Builder) Len

func (b *Builder) Len() int

Len returns the length of the underlying byte slice.

func (*Builder) Reset

func (b *Builder) Reset()

Reset resets the underlying byte slice.

Subsequent writes will re-use the slice's backing array.

func (*Builder) ResetBytes

func (b *Builder) ResetBytes(bs []byte)

ResetBytes resets the underlying byte slice to bs.

func (*Builder) String

func (b *Builder) String() string

String returns a string copy of the underlying byte slice.

func (*Builder) TrimNewline

func (b *Builder) TrimNewline()

TrimNewline trims any final "\n" byte from the end of the buffer.

func (*Builder) TruncateAfter

func (b *Builder) TruncateAfter(n int)

TruncateAfter truncates and discards last n bytes.

It will is equal to reset if n is greater than the length of the underlying byte slice,

func (*Builder) TruncateBefore

func (b *Builder) TruncateBefore(n int)

TruncateBefore truncates and discards first n bytes.

It will is equal to reset if n is greater than the length of the underlying byte slice,

func (*Builder) Write

func (b *Builder) Write(bs []byte) (int, error)

Write implements io.Writer.

func (*Builder) WriteByte

func (b *Builder) WriteByte(c byte) error

WriteByte writes a byte into the builder.

func (*Builder) WriteRune

func (b *Builder) WriteRune(r rune) (int, error)

WriteRune writes a rune into the builder.

func (*Builder) WriteString

func (b *Builder) WriteString(s string) (int, error)

WriteString writes a string into the builder.

func (*Builder) WriteTo

func (b *Builder) WriteTo(w io.Writer) (int64, error)

WriteTo implements io.WriterTo.

type Encoder

type Encoder func(buf *Builder, r Record)

Encoder is the encoder of the log record.

Notice: w is the buffer writer.

func JSONEncoder

func JSONEncoder() Encoder

JSONEncoder encodes the key-values log as json.

Notice: the key name of the level is "lvl" and that of the time is "t" with time.RFC3339Nano, and that of the message is "msg". If the logger name exists, it will encode it and the key name is "logger".

func NothingEncoder

func NothingEncoder() Encoder

NothingEncoder encodes nothing.

func StdJSONEncoder

func StdJSONEncoder() Encoder

StdJSONEncoder is equal to JSONEncoder, which uses json.Marshal() to encode it, but the performance is a little bad.

func TextEncoder

func TextEncoder() Encoder

TextEncoder encodes the key-values log as the text.

Notice: the key name of the level is "lvl", that of the time is "t" with time.RFC3339Nano, and that of the message is "msg". If the logger name exists, it will encode it and the key name is "logger".

type Field

type Field struct {
	Key   string
	Value interface{}
}

Field represents a key-value pair.

type FmtLogger

type FmtLogger interface {
	Writer() io.Writer

	Trace(format string, args ...interface{})
	Debug(format string, args ...interface{})
	Info(format string, args ...interface{})
	Warn(format string, args ...interface{})
	Error(format string, args ...interface{})
	Panic(format string, args ...interface{})
	Fatal(format string, args ...interface{})
}

FmtLogger represents a logger based on the % foramtter.

func ToFmtLogger

func ToFmtLogger(logger Logger) FmtLogger

ToFmtLogger converts Logger to FmtLogger.

type FmtLoggerError

type FmtLoggerError interface {
	Writer() io.Writer

	Trace(format string, args ...interface{}) error
	Debug(format string, args ...interface{}) error
	Info(format string, args ...interface{}) error
	Warn(format string, args ...interface{}) error
	Error(format string, args ...interface{}) error
	Panic(format string, args ...interface{}) error
	Fatal(format string, args ...interface{}) error
}

FmtLoggerError represents a logger based on the % foramtter.

func ToFmtLoggerError

func ToFmtLoggerError(logger Logger) FmtLoggerError

ToFmtLoggerError converts Logger to FmtLoggerError.

type Hook

type Hook func(name string, level Level) bool

Hook is a log hook, which receives the logger name and the log level and reports whether the log should continue to be emitted.

Notice: You can use it to sample the log.

func DisableLogger

func DisableLogger(names ...string) Hook

DisableLogger disables the logger, whose name is in names, to emit the log.

func DisableLoggerFromEnv

func DisableLoggerFromEnv(environ string) Hook

DisableLoggerFromEnv is the same as DisableLogger, but get the names from the environ.

The environ format is "environ=value", and `value` is like "name=off|0[,name=off|0]*". So, for `DisableLoggerFromEnv("mod")`, the environ variable

mod=n1=0,n2=off,n3=on,n4=1

the loggers named "n1" and "n2" will be disabled, and others, including "n3" and "n4", will be enabled.

func EnableLogger

func EnableLogger(names ...string) Hook

EnableLogger allows the logger, whose name is in names, to emit the log.

func EnableLoggerFromEnv

func EnableLoggerFromEnv(environ string) Hook

EnableLoggerFromEnv is the same as EnableLogger, but get the names from the environ.

The environ format is "environ=value", and `value` is like "name=on|1[,name=on|1]*". So, for `EnableLoggerFromEnv("mod")`, the environ variable

mod=n1=0,n2=off,n3=on,n4=1

the loggers named "n3" and "n4" will be enabled, and others, including "n1" and "n2", will be disabled.

type Level

type Level int32

Level represents a level. The bigger the value, the higher the level.

const (
	LvlTrace Level = iota * 100
	LvlDebug
	LvlInfo
	LvlWarn
	LvlError
	LvlPanic
	LvlFatal
)

Predefine some levels.

You can define yourself level.

For LvlFatal or higher, it will emit the log and call the clean functions firstly, then the program will exit by calling `os.Exit(1)`.

For LvlPanic or higher, it will emit the log firstly, then panic with Record, but the field Fields is reset to nil.

func NameToLevel

func NameToLevel(name string, defaultPanic ...bool) Level

NameToLevel returns the Level by the name, which is case Insensitive.

If not panic, it will return `LvlInfo` instead if no level named `name`.

func (Level) MarshalJSON

func (l Level) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Level) String

func (l Level) String() string

func (Level) WriteTo

func (l Level) WriteTo(out io.Writer) (int64, error)

WriteTo implements io.WriterTo.

type Log

type Log struct {
	// contains filtered or unexported fields
}

Log is used to emit a structured key-value log.

func Debug

func Debug(fields ...Field) Log

Debug emits a DEBUG log.

func Error

func Error(fields ...Field) Log

Error emits a ERROR log.

func Fatal

func Fatal(fields ...Field) Log

Fatal emits a FATAL log.

func Info

func Info(fields ...Field) Log

Info emits a INFO log.

func L

func L(level Level, fields ...Field) Log

L emits a customized level log.

func Panic

func Panic(fields ...Field) Log

Panic emits a PANIC log.

func Trace

func Trace(fields ...Field) Log

Trace emits a TRACE log.

func Warn

func Warn(fields ...Field) Log

Warn emits a WARN log.

func (Log) F

func (l Log) F(fields ...Field) Log

F appends more than one key-value pair into the structured log by the field.

func (Log) K

func (l Log) K(key string, value interface{}) Log

K appends the key-value pair into the structured log.

func (Log) Msg

func (l Log) Msg(args ...interface{})

Msg appends the msg into the structured log with the key "msg" at last.

Notice: "args" will be formatted by `fmt.Sprint(args...)`.

func (Log) Msgf

func (l Log) Msgf(format string, args ...interface{})

Msgf appends the msg into the structured log with the key "msg" at last.

Notice: "format" and "args" will be foramtted by `fmt.Sprintf(format, args...)`.

func (Log) Print

func (l Log) Print(args ...interface{})

Print is equal to l.Msg(args...).

func (Log) Printf

func (l Log) Printf(format string, args ...interface{})

Printf is equal to l.Msgf(format, args...).

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger is a structured logger based on key-value.

func New

func New(w ...Writer) Logger

New returns a new Logger with the writer w that is os.Stdout by default.

The default level is `LvlDebug`, and the default encoder is `TextEncoder()`.

func NewSimpleLogger

func NewSimpleLogger(level, filePath, fileSize string, fileNum int) (Logger, error)

NewSimpleLogger returns a new Logger based on the file writer by using `SizedRotatingFile`.

If filePath is "", it will ignore fileSize and fileNum, and use os.Stdout as the writer. If fileSize is "", it is "100M" by default. And fileNum is 100 by default.

func (Logger) Debug

func (l Logger) Debug(fields ...Field) Log

Debug is equal to l.Level(LvlDebug, fields...).

func (Logger) Error

func (l Logger) Error(fields ...Field) Log

Error is equal to l.Level(LvlError, fields...).

func (Logger) Fatal

func (l Logger) Fatal(fields ...Field) Log

Fatal is equal to l.Level(LvlFatal, fields...).

func (Logger) GetDepth

func (l Logger) GetDepth() int

GetDepth returns the depth of the caller stack.

func (Logger) GetLevel

func (l Logger) GetLevel() Level

GetLevel returns the logger level.

func (Logger) GetName

func (l Logger) GetName() string

GetName returns the logger name.

func (Logger) GetWriter

func (l Logger) GetWriter() Writer

GetWriter returns the logger writer.

func (Logger) Info

func (l Logger) Info(fields ...Field) Log

Info is equal to l.Level(LvlInfo, fields...).

func (Logger) L

func (l Logger) L(level Level, fields ...Field) Log

L is short for Level(level, fields...).

func (Logger) Level

func (l Logger) Level(level Level, fields ...Field) Log

Level emits a log, the level of which is level.

You can gives some key-value field contexts optionally, which is equal to call Log.F(fields...).

func (Logger) Panic

func (l Logger) Panic(fields ...Field) Log

Panic is equal to l.Level(LvlPanic, fields...).

func (Logger) Trace

func (l Logger) Trace(fields ...Field) Log

Trace is equal to l.Level(LvlTrace, fields...).

func (Logger) Warn

func (l Logger) Warn(fields ...Field) Log

Warn is equal to l.Level(LvlWarn, fields...).

func (Logger) WithDepth

func (l Logger) WithDepth(depth int) Logger

WithDepth returns a new Logger with the caller depth.

Notice: 0 stands for the stack where the caller is.

func (Logger) WithEncoder

func (l Logger) WithEncoder(encoder Encoder) Logger

WithEncoder returns a new Logger with the encoder.

func (Logger) WithField

func (l Logger) WithField(fields ...Field) Logger

WithField returns a new Logger with the new field context.

func (Logger) WithHook

func (l Logger) WithHook(hook ...Hook) Logger

WithHook returns a new Logger with the hook, which will append the hook.

func (Logger) WithKv

func (l Logger) WithKv(key string, value interface{}) Logger

WithKv returns a new Logger with the new key-value context, which is equal to

l.WithField(Field{Key: key, Value: value})

func (Logger) WithLevel

func (l Logger) WithLevel(level Level) Logger

WithLevel returns a new Logger with the level.

func (Logger) WithName

func (l Logger) WithName(name string) Logger

WithName returns a new Logger with the name.

func (Logger) WithWriter

func (l Logger) WithWriter(w Writer) Logger

WithWriter returns a new Logger with the writer w.

type Record

type Record struct {
	Msg    string    // The log message
	Time   time.Time // The start time when to emit the log
	Name   string    // The logger name
	Depth  int       // The depth of the caller
	Level  Level     // The log level
	Fields []Field   // The key-value logs
}

Record represents a log record.

type SizedRotatingFile

type SizedRotatingFile struct {
	// contains filtered or unexported fields
}

SizedRotatingFile is a file rotating logging handler based on the size.

func NewSizedRotatingFile

func NewSizedRotatingFile(filename string, size, count int,
	mode ...os.FileMode) (*SizedRotatingFile, error)

NewSizedRotatingFile returns a new SizedRotatingFile.

It is thread-safe for concurrent writes.

The default permission of the log file is 0644.

func (*SizedRotatingFile) Close

func (f *SizedRotatingFile) Close() (err error)

Close implements io.Closer.

func (*SizedRotatingFile) Flush

func (f *SizedRotatingFile) Flush() error

Flush flushes the data to the underlying disk.

func (*SizedRotatingFile) Write

func (f *SizedRotatingFile) Write(data []byte) (n int, err error)

Write implements io.Writer.

type Valuer

type Valuer func(Record) (v interface{})

Valuer is used to represent a lazy value by calling a function.

func Caller

func Caller(fullPath ...bool) Valuer

Caller returns a Valuer that returns the caller "file:line".

If fullPath is true, the file is the full path but removing the GOPATH prefix.

func CallerStack

func CallerStack(fullPath ...bool) Valuer

CallerStack returns a Valuer returning the caller stack without runtime.

If fullPath is true, the file is the full path but removing the GOPATH prefix.

func FileLongName

func FileLongName() Valuer

FileLongName returns the long name of the file where the caller is in.

func FileName

func FileName() Valuer

FileName returns the short name of the file where the caller is in.

func FuncFullName

func FuncFullName() Valuer

FuncFullName returns the full name of the function where the caller is in.

func FuncName

func FuncName() Valuer

FuncName returns the name of the function where the caller is in.

func LineNo

func LineNo() Valuer

LineNo returns the line number of the caller as string.

func LineNoAsInt

func LineNoAsInt() Valuer

LineNoAsInt returns the line number of the caller.

Return 0 if the line is missing.

func Package

func Package() Valuer

Package returns the name of the package where the caller is in.

type Writer

type Writer interface {
	io.Closer
	Write(level Level, data []byte) (n int, err error)
}

Writer is the interface to write the log to the underlying storage.

func DiscardWriter

func DiscardWriter() Writer

DiscardWriter discards all the data.

func FailoverWriter

func FailoverWriter(outs ...Writer) Writer

FailoverWriter writes all log records to the first handler specified, but will failover and write to the second handler if the first handler has failed, and so on for all handlers specified.

For example, you might want to log to a network socket, but failover to writing to a file if the network fails, and then to standard out if the file write fails.

func LevelWriter

func LevelWriter(lvl Level, w Writer) Writer

LevelWriter filters the logs whose level is less than lvl.

func MultiWriter

func MultiWriter(outs ...Writer) Writer

MultiWriter writes one data to more than one destination.

func NetWriter

func NetWriter(network, addr string) (Writer, error)

NetWriter opens a socket to the given address and writes the log over the connection.

Notice: it will be wrapped by SafeWriter, so it's thread-safe.

func ReopenWriter

func ReopenWriter(factory func() (w io.WriteCloser, reopen <-chan bool, err error)) Writer

ReopenWriter returns a writer that can be closed then re-opened, which is used for logrotate typically.

Notice: It's thread-safe.

func SafeWriter

func SafeWriter(w Writer) Writer

SafeWriter is guaranteed that only a single writing operation can proceed at a time.

The returned Writer supports io.Closer, which will be forwarded to w.Close().

It's necessary for thread-safe concurrent writes.

func StreamWriter

func StreamWriter(w io.Writer) Writer

StreamWriter converts io.Writer to Writer.

If w has implemented io.Closer, the returned writer will forward the Close calling to it. Or do nothing.

func SyslogNetWriter

func SyslogNetWriter(net, addr string, priority syslog.Priority, tag string) (Writer, error)

SyslogNetWriter opens a connection to a log daemon over the network and writes all logs to it.

func SyslogWriter

func SyslogWriter(priority syslog.Priority, tag string) (Writer, error)

SyslogWriter opens a connection to the system syslog daemon by calling syslog.New and writes all logs to it.

func WriterFunc

func WriterFunc(w func(Level, []byte) (int, error), close ...func() error) Writer

WriterFunc adapts a function with w to Writer.

If giving the close function, it will be called when closing the writer. Or do nothing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL