import "github.com/phuslu/log"
async.go console.go console_unix.go file.go formatter.go goid.go grpc.go journal.go level.go logger.go logr.go multi.go stdlog.go syslog.go time_linux.go tsv.go xid.go
const ErrInvalidXID = xidError("xid: invalid XID")
ErrInvalidXID is returned when trying to parse an invalid XID
const TimeFormatUnix = "\x01"
TimeFormatUnix defines a time format that makes time fields to be serialized as Unix timestamp integers.
const TimeFormatUnixMs = "\x02"
TimeFormatUnixMs defines a time format that makes time fields to be serialized as Unix timestamp integers in milliseconds.
var DefaultLogger = Logger{ Level: DebugLevel, Caller: 0, TimeField: "", TimeFormat: "", Writer: IOWriter{os.Stderr}, }
DefaultLogger is the global logger.
Fastrandn returns a pseudorandom uint32 in [0,n).
Goid returns the current goroutine id. It exactly matches goroutine id of the stack trace.
IsTerminal returns whether the given file descriptor is a terminal.
Printf sends a log entry without extra field. Arguments are handled in the manner of fmt.Printf.
type AsyncWriter struct { // ChannelSize is the size of the data channel, the default size is 1. ChannelSize uint // Writer specifies the writer of output. Writer Writer // contains filtered or unexported fields }
AsyncWriter is an Writer that writes asynchronously.
func (w *AsyncWriter) Close() (err error)
Close implements io.Closer, and closes the underlying Writer.
func (w *AsyncWriter) WriteEntry(e *Entry) (int, error)
WriteEntry implements Writer.
type ConsoleWriter struct { // ColorOutput determines if used colorized output. ColorOutput bool // QuoteString determines if quoting string values. QuoteString bool // EndWithMessage determines if output message in the end. EndWithMessage bool // Formatter specifies an optional text formatter for creating a customized output, // If it is set, ColorOutput, QuoteString and EndWithMessage will be ignore. Formatter func(w io.Writer, args *FormatterArgs) (n int, err error) // Writer is the output destination. using os.Stderr if empty. Writer io.Writer }
ConsoleWriter parses the JSON input and writes it in a colorized, human-friendly format to Writer. IMPORTANT: Don't use ConsoleWriter on critical path of a high concurrency and low latency application.
Default output format:
{Time} {Level} {Goid} {Caller} > {Message} {Key}={Value} {Key}={Value}
Note: The performance of ConsoleWriter is not good enough, because it will parses JSON input into structured records, then output in a specific order. Roughly 2x faster than logrus.TextFormatter, 0.8x fast as zap.ConsoleEncoder, and 5x faster than zerolog.ConsoleWriter.
func (w *ConsoleWriter) Close() (err error)
Close implements io.Closer, will closes the underlying Writer if not empty.
func (w *ConsoleWriter) Write(p []byte) (int, error)
Write implements io.Writer
func (w *ConsoleWriter) WriteEntry(e *Entry) (int, error)
WriteEntry implements Writer.
Context represents contextual fields.
Entry represents a log entry. It is instanced by one of the level method of Logger and finalized by the Msg or Msgf method.
Debug starts a new message with debug level.
Error starts a new message with error level.
Fatal starts a new message with fatal level.
Info starts a new message with info level.
NewContext starts a new contextual entry.
Panic starts a new message with panic level.
Trace starts a new message with trace level.
Warn starts a new message with warning level.
AnErr adds the field key with serialized err to the logger context.
Bool append append the val as a bool to the entry.
Bools adds the field key with val as a []bool to the entry.
Byte adds the field key with val as a byte to the entry.
Bytes adds the field key with val as a string to the entry.
BytesOrNil adds the field key with val as a string or nil to the entry.
Caller adds the file:line of the "caller" key.
Context sends the contextual fields to entry.
Dict sends the contextual fields with key to entry.
Discard disables the entry so Msg(f) won't print it.
Dur adds the field key with duration d to the entry.
Durs adds the field key with val as a []time.Duration to the entry.
func (e *Entry) EmbedObject(obj LogObjectMarshaler) *Entry
EmbedObject marshals and Embeds an object that implement the LogObjectMarshaler interface.
Enabled return false if the entry is going to be filtered out by log level.
Err adds the field "error" with serialized err to the entry.
Errs adds the field key with errs as an array of serialized errors to the entry.
Fields is a helper function to use a map to set fields using type assertion.
Float32 adds the field key with f as a float32 to the entry.
Float64 adds the field key with f as a float64 to the entry.
Floats32 adds the field key with f as a []float32 to the entry.
Floats64 adds the field key with f as a []float64 to the entry.
GoStringer adds the field key with val.GoStringer() to the entry.
Hex adds the field key with val as a hex string to the entry.
IPAddr adds IPv4 or IPv6 Address to the entry.
IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the entry.
Int adds the field key with i as a int to the entry.
Int16 adds the field key with i as a int16 to the entry.
Int32 adds the field key with i as a int32 to the entry.
Int64 adds the field key with i as a int64 to the entry.
Int8 adds the field key with i as a int8 to the entry.
Interface adds the field key with i marshaled using reflection.
KeysAndValues sends keysAndValues to Entry
MACAddr adds MAC address to the entry.
Msg sends the entry with msg added as the message field if not empty.
Msgf sends the entry with formatted msg added as the message field if not empty.
Msgv sends the entry with msgs added as the message field if not empty.
func (e *Entry) Object(key string, obj LogObjectMarshaler) *Entry
Object marshals an object that implement the LogObjectMarshaler interface.
RawJSON adds already encoded JSON to the log line under key.
RawJSONStr adds already encoded JSON String to the log line under key.
Stack enables stack trace printing for the error passed to Err().
Str adds the field key with val as a string to the entry.
StrInt adds the field key with integer val as a string to the entry.
Stringer adds the field key with val.String() to the entry.
Strs adds the field key with vals as a []string to the entry.
Time append append t formated as string using time.RFC3339Nano.
TimeDiff adds the field key with positive duration between time t and start. If time t is not greater than start, duration will be 0. Duration format follows the same principle as Dur().
TimeFormat append append t formated as string using timefmt.
Uint adds the field key with i as a uint to the entry.
Uint16 adds the field key with i as a uint16 to the entry.
Uint32 adds the field key with i as a uint32 to the entry.
Uint64 adds the field key with i as a uint64 to the entry.
Uint8 adds the field key with i as a uint8 to the entry.
Value builds the contextual fields.
Xid adds the field key with xid.ID as a base32 string to the entry.
Event is an alias for Entry
Deprecated: Use Entry instead.
type FileWriter struct { // Filename is the file to write logs to. Backup log files will be retained // in the same directory. Filename string // MaxSize is the maximum size in bytes of the log file before it gets rotated. MaxSize int64 // MaxBackups is the maximum number of old log files to retain. The default // is to retain all old log files MaxBackups int // FileMode represents the file's mode and permission bits. The default // mode is 0644 FileMode os.FileMode // TimeFormat specifies the time format of filename, uses `2006-01-02T15-04-05` as default format. // If set with `TimeFormatUnix`, `TimeFormatUnixMs`, times are formated as UNIX timestamp. TimeFormat string // LocalTime determines if the time used for formatting the timestamps in // log files is the computer's local time. The default is to use UTC time. LocalTime bool // HostName determines if the hostname used for formatting in log files. HostName bool // ProcessID determines if the pid used for formatting in log files. ProcessID bool // EnsureFolder ensures the file directory creation before writing. EnsureFolder bool // Cleaner specifies an optional cleanup function of log backups after rotation, // if not set, the default behavior is to delete more than MaxBackups log files. Cleaner func(filename string, maxBackups int, matches []os.FileInfo) // contains filtered or unexported fields }
FileWriter is an Writer that writes to the specified filename.
Backups use the log file name given to FileWriter, in the form `name.timestamp.ext` where name is the filename without the extension, timestamp is the time at which the log was rotated formatted with the time.Time format of `2006-01-02T15-04-05` and the extension is the original extension. For example, if your FileWriter.Filename is `/var/log/foo/server.log`, a backup created at 6:30pm on Nov 11 2016 would use the filename `/var/log/foo/server.2016-11-04T18-30-00.log`
Whenever a new logfile gets created, old log files may be deleted. The most recent files according to filesystem modified time will be retained, up to a number equal to MaxBackups (or all of them if MaxBackups is 0). Any files with an encoded timestamp older than MaxAge days are deleted, regardless of MaxBackups. Note that the time encoded in the timestamp is the rotation time, which may differ from the last time that file was written to.
func (w *FileWriter) Close() (err error)
Close implements io.Closer, and closes the current logfile.
func (w *FileWriter) Rotate() (err error)
Rotate causes Logger to close the existing log file and immediately create a new one. This is a helper function for applications that want to initiate rotations outside of the normal rotation rules, such as in response to SIGHUP. After rotating, this initiates compression and removal of old log files according to the configuration.
func (w *FileWriter) Write(p []byte) (n int, err error)
Write implements io.Writer. If a write would cause the log file to be larger than MaxSize, the file is closed, rotate to include a timestamp of the current time, and update symlink with log name file to the new file.
func (w *FileWriter) WriteEntry(e *Entry) (n int, err error)
WriteEntry implements Writer. If a write would cause the log file to be larger than MaxSize, the file is closed, rotate to include a timestamp of the current time, and update symlink with log name file to the new file.
type FormatterArgs struct { Time string // "2019-07-10T05:35:54.277Z" Message string // "a structure message" Level string // "info" Caller string // "prog.go:42" Goid string // "123" Stack string // "<stack string>" KeyValues []struct { Key string // "foo" Value string // "bar" ValueType byte // 's' } }
FormatterArgs is a parsed sturct from json input
func (args *FormatterArgs) Get(key string) (value string)
type GrpcLogger struct {
// contains filtered or unexported fields
}
GrpcLogger implements methods to satisfy interface google.golang.org/grpc/grpclog.LoggerV2.
func (g *GrpcLogger) Error(args ...interface{})
Error logs to ERROR log. Arguments are handled in the manner of fmt.Print.
func (g *GrpcLogger) Errorf(format string, args ...interface{})
Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
func (g *GrpcLogger) Errorln(args ...interface{})
Errorln logs to ERROR log. Arguments are handled in the manner of fmt.Println.
func (g *GrpcLogger) Fatal(args ...interface{})
Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Print. gRPC ensures that all Fatal logs will exit with os.Exit(1). Implementations may also call os.Exit() with a non-zero exit code.
func (g *GrpcLogger) Fatalf(format string, args ...interface{})
Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. gRPC ensures that all Fatal logs will exit with os.Exit(1). Implementations may also call os.Exit() with a non-zero exit code.
func (g *GrpcLogger) Fatalln(args ...interface{})
Fatalln logs to ERROR log. Arguments are handled in the manner of fmt.Println. gRPC ensures that all Fatal logs will exit with os.Exit(1). Implementations may also call os.Exit() with a non-zero exit code.
func (g *GrpcLogger) Info(args ...interface{})
Info logs to INFO log. Arguments are handled in the manner of fmt.Print.
func (g *GrpcLogger) Infof(format string, args ...interface{})
Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf.
func (g *GrpcLogger) Infoln(args ...interface{})
Infoln logs to INFO log. Arguments are handled in the manner of fmt.Println.
func (g *GrpcLogger) V(level int) bool
V reports whether verbosity level l is at least the requested verbose leveg.
func (g *GrpcLogger) Warning(args ...interface{})
Warning logs to WARNING log. Arguments are handled in the manner of fmt.Print.
func (g *GrpcLogger) Warningf(format string, args ...interface{})
Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf.
func (g *GrpcLogger) Warningln(args ...interface{})
Warningln logs to WARNING log. Arguments are handled in the manner of fmt.Println.
IOWriter wraps an io.Writer to Writer.
WriteEntry implements Writer.
type JournalWriter struct { // JournalSocket specifies socket name, using `/run/systemd/journal/socket` if empty. JournalSocket string // contains filtered or unexported fields }
JournalWriter is an Writer that writes logs to journald.
func (w *JournalWriter) Close() (err error)
Close implements io.Closer.
func (w *JournalWriter) WriteEntry(e *Entry) (n int, err error)
WriteEntry implements Writer.
Level defines log levels.
const ( // TraceLevel defines trace log level. TraceLevel Level = 1 // DebugLevel defines debug log level. DebugLevel Level = 2 // InfoLevel defines info log level. InfoLevel Level = 3 // WarnLevel defines warn log level. WarnLevel Level = 4 // ErrorLevel defines error log level. ErrorLevel Level = 5 // FatalLevel defines fatal log level. FatalLevel Level = 6 // PanicLevel defines panic log level. PanicLevel Level = 7 )
ParseLevel converts a level string into a log Level value.
String return lowe case string of Level
LogObjectMarshaler provides a strongly-typed and encoding-agnostic interface to be implemented by types used with Entry's Object methods.
type Logger struct { // Level defines log levels. Level Level // Caller determines if adds the file:line of the "caller" key. Caller int // TimeField defines the time filed name in output. It uses "time" in if empty. TimeField string // TimeFormat specifies the time format in output. It uses time.RFC3339 with milliseconds if empty. // If set with `TimeFormatUnix`, `TimeFormatUnixMs`, times are formated as UNIX timestamp. TimeFormat string // Writer specifies the writer of output. It uses a wrapped os.Stderr Writer in if empty. Writer Writer }
A Logger represents an active logging object that generates lines of JSON output to an io.Writer.
Debug starts a new message with debug level.
Error starts a new message with error level.
Fatal starts a new message with fatal level.
func (l *Logger) Grpc(context Context) (g *GrpcLogger)
Grpc wraps the Logger to provide a LoggerV2 logger
Info starts a new message with info level.
Log starts a new message with no level.
func (l *Logger) Logr(context Context) *LogrLogger
Logr wraps the Logger to provide a logr logger
Panic starts a new message with panic level.
Printf sends a log entry without extra field. Arguments are handled in the manner of fmt.Printf.
SetLevel changes logger default level.
Std wraps the Logger to provide *stdLog.Logger
Trace starts a new message with trace level.
Warn starts a new message with warning level.
WithLevel starts a new message with level.
type LogrLogger struct {
// contains filtered or unexported fields
}
LogrLogger implements methods to satisfy interface github.com/go-logr/logr.Logger.
func (l *LogrLogger) Enabled() bool
Enabled tests whether this Logger is enabled. For example, commandline flags might be used to set the logging verbosity and disable some info logs.
func (l *LogrLogger) Error(err error, msg string, keysAndValues ...interface{})
Error logs an error, with the given message and key/value pairs as context. It functions similarly to calling Info with the "error" named value, but may have unique behavior, and should be preferred for logging errors (see the package documentations for more information).
The msg field should be used to add context to any underlying error, while the err field should be used to attach the actual error that triggered this log line, if present.
func (l *LogrLogger) Info(msg string, keysAndValues ...interface{})
Info logs a non-error message with the given key/value pairs as context.
The msg argument should be used to add some constant description to the log line. The key/value pairs can then be used to add additional variable information. The key/value pairs should alternate string keys and arbitrary values.
func (l *LogrLogger) V(level int) *LogrLogger
V returns an Logger value for a specific verbosity level, relative to this Logger. In other words, V values are additive. V higher verbosity level means a log message is less important. It's illegal to pass a log level less than zero.
func (l *LogrLogger) WithName(name string) *LogrLogger
WithName adds a new element to the logger's name. Successive calls with WithName continue to append suffixes to the logger's name. It's strongly recommended that name segments contain only letters, digits, and hyphens (see the package documentation for more information).
func (l *LogrLogger) WithValues(keysAndValues ...interface{}) *LogrLogger
WithValues adds some key-value pairs of context to a logger. See Info for documentation on how key/value pairs work.
type MultiWriter struct { // InfoWriter specifies all the level logs writes to InfoWriter Writer // WarnWriter specifies the level greater than or equal to WarnLevel writes to WarnWriter Writer // WarnWriter specifies the level greater than or equal to ErrorLevel writes to ErrorWriter Writer // ConsoleWriter specifies the console writer ConsoleWriter Writer // ConsoleLevel specifies the level greater than or equal to it also writes to ConsoleLevel Level }
MultiWriter is an Writer that log to different writers by different levels
func (w *MultiWriter) Close() (err error)
Close implements io.Closer, and closes the underlying LeveledWriter.
func (w *MultiWriter) WriteEntry(e *Entry) (n int, err error)
WriteEntry implements entryWriter.
type SyslogWriter struct { // Network specifies network of the syslog server Network string // Address specifies address of the syslog server Address string // Hostname specifies hostname of the syslog message Hostname string // Tag specifies tag of the syslog message Tag string // Marker specifies prefix of the syslog message, e.g. `@cee:` Marker string // Dial specifies the dial function for creating TCP/TLS connections. Dial func(network, addr string) (net.Conn, error) // contains filtered or unexported fields }
SyslogWriter is an Writer that writes logs to a syslog server..
func (w *SyslogWriter) Close() (err error)
Close closes a connection to the syslog server.
func (w *SyslogWriter) WriteEntry(e *Entry) (n int, err error)
WriteEntry implements Writer, sends logs with priority to the syslog server.
type TSVEntry struct {
// contains filtered or unexported fields
}
TSVEntry represents a tsv log entry. It is instanced by one of TSVLogger and finalized by the Msg method.
Bool append the b as a bool to the entry.
Byte append the b as a byte to the entry.
Bytes adds a bytes as string to the entry.
Float32 adds a float32 to the entry.
Float64 adds a float64 to the entry.
IPAddr adds IPv4 or IPv6 Address to the entry.
Int adds a int to the entry.
Int16 adds a int16 to the entry.
Int32 adds a int32 to the entry.
Int64 adds a int64 to the entry.
Int8 adds a int8 to the entry.
Msg sends the entry.
Str adds a string to the entry.
Timestamp adds the current time as UNIX timestamp
TimestampMS adds the current time with milliseconds as UNIX timestamp
Uint adds a uint to the entry.
Uint16 adds a uint16 to the entry.
Uint32 adds a uint32 to the entry.
Uint64 adds a uint64 to the entry.
Uint8 adds a uint8 to the entry.
TSVLogger represents an active logging object that generates lines of TSV output to an io.Writer.
New starts a new tsv message.
Writer defines an entry writer interface.
XID represents a unique request id
NewXID generates a globally unique XID
NewXIDWithTime generates a globally unique XID with unix timestamp
ParseXID parses an XID from its string representation
Counter returns the incrementing value part of the id.
Machine returns the 3-byte machine id part of the id.
MarshalJSON implements encoding/json Marshaler interface
MarshalText implements encoding/text TextMarshaler interface
Pid returns the process id part of the id.
String returns a base32 hex lowercased representation of the id.
Time returns the timestamp part of the id.
UnmarshalJSON implements encoding/json Unmarshaler interface
UnmarshalText implements encoding/text TextUnmarshaler interface
Package log imports 22 packages (graph) and is imported by 6 packages. Updated 2021-01-08. Refresh now. Tools for package owners.