log

package
v0.0.0-...-ad86efc Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2016 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Overview

Package log implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. It provides functions Info, Warning, Error, Fatal, plus formatting variants such as Infof. It also provides V-style logging and adaptions for use as a structured logging engine.

Basic examples:

	log.Info("Prepare to repel boarders")

	log.Fatal("Initialization failed", err)

 // Log with context.
 log.Infoc(context, "client error: %s", err)

See the documentation for the V function for an explanation of these examples:

if log.V(2) {
	log.Info("Starting transaction...")
}

Log output is buffered and written periodically using Flush. Programs should call Flush before exiting to guarantee all log output is written.

By default, all log statements write to files in a temporary directory. This package provides several flags that modify this behavior. These are provided via the pflags library; see InitFlags.

--logtostderr=true
	Logs are written to standard error instead of to files.
--alsologtostderr=INFO
	Logs are written to standard error as well as to files.
--log-dir=""
	Log files will be written to this directory instead of the
	default temporary directory.

Other flags provide aids to debugging.

--log-backtrace-at=""
	When set to a file and line number holding a logging statement,
	such as
		-log_backtrace_at=gopherflakes.go:234
	a stack trace will be written to the Info log whenever execution
	hits that statement. (Unlike with --vmodule, the ".go" must be
	present.)
--verbosity=0
	Enable V-leveled logging at the specified level.
--vmodule=""
	The syntax of the argument is a comma-separated list of pattern=N,
	where pattern is a literal file name (minus the ".go" suffix) or
	"glob" pattern and N is a V level. For instance,
		-vmodule=gopher*=3
	sets the V level to 3 in all Go files whose names begin "gopher".

Package log is a generated protocol buffer package.

It is generated from these files:
	cockroach/util/log/log.proto

It has these top-level messages:
	Entry
	FileDetails
	FileInfo

Index

Constants

View Source
const DynamicIntValueUnknown = math.MinInt64

DynamicIntValueUnknown can be used with Set; it makes the value "?".

Variables

View Source
var (
	ErrInvalidLengthLog = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowLog   = fmt.Errorf("proto: integer overflow")
)
View Source
var MaxSize uint64 = 1024 * 1024 * 10

MaxSize is the maximum size of a log file in bytes.

View Source
var Severity_name = map[int32]string{
	0: "UNKNOWN",
	1: "INFO",
	2: "WARNING",
	3: "ERROR",
	4: "FATAL",
	5: "NONE",
}
View Source
var Severity_value = map[string]int32{
	"UNKNOWN": 0,
	"INFO":    1,
	"WARNING": 2,
	"ERROR":   3,
	"FATAL":   4,
	"NONE":    5,
}
View Source
var Stats struct {
	Info, Warning, Error outputStats
}

Stats tracks the number of lines of output and number of bytes per severity level. Values must be read with atomic.LoadInt64.

Functions

func DirSet

func DirSet() bool

DirSet returns true of the log directory has been changed from its default.

func DisableLogFileOutput

func DisableLogFileOutput()

DisableLogFileOutput turns off logging. For unittesting only.

func EnableLogFileOutput

func EnableLogFileOutput(dir string)

EnableLogFileOutput turns on logging using the specified directory. For unittesting only.

func ErrEvent

func ErrEvent(ctx context.Context, msg string)

ErrEvent looks for an opentracing.Trace in the context and logs the given message to it. If no Trace is found, it looks for an EventLog in the context and logs the message to it (as an error). If neither is found, does nothing.

func ErrEventf

func ErrEventf(ctx context.Context, format string, args ...interface{})

ErrEventf looks for an opentracing.Trace in the context and formats and logs the given message to it. If no Trace is found, it looks for an EventLog in the context and formats and logs the message to it (as an error). If neither is found, does nothing.

func Error

func Error(ctx context.Context, args ...interface{})

Error logs to the ERROR, WARNING, and INFO logs. It extracts log tags from the context and logs them along with the given message. Arguments are handled in the manner of fmt.Print; a newline is appended.

func Errorf

func Errorf(ctx context.Context, format string, args ...interface{})

Errorf logs to the ERROR, WARNING, and INFO logs. It extracts log tags from the context and logs them along with the given message. Arguments are handled in the manner of fmt.Printf; a newline is appended.

func ErrorfDepth

func ErrorfDepth(ctx context.Context, depth int, format string, args ...interface{})

ErrorfDepth logs to the ERROR, WARNING, and INFO logs, offsetting the caller's stack frame by 'depth'. It extracts log tags from the context and logs them along with the given message. Arguments are handled in the manner of fmt.Printf; a newline is appended.

func Event

func Event(ctx context.Context, msg string)

Event looks for an opentracing.Trace in the context and logs the given message to it. If no Trace is found, it looks for an EventLog in the context and logs the message to it. If neither is found, does nothing.

func Eventf

func Eventf(ctx context.Context, format string, args ...interface{})

Eventf looks for an opentracing.Trace in the context and formats and logs the given message to it. If no Trace is found, it looks for an EventLog in the context and logs the message to it. If neither is found, does nothing.

func Fatal

func Fatal(ctx context.Context, args ...interface{})

Fatal logs to the INFO, WARNING, ERROR, and FATAL logs, including a stack trace of all running goroutines, then calls os.Exit(255). It extracts log tags from the context and logs them along with the given message. Arguments are handled in the manner of fmt.Print; a newline is appended.

func FatalOnPanic

func FatalOnPanic()

FatalOnPanic recovers from a panic and exits the process with a Fatal log. This is useful for avoiding a panic being caught through a CGo exported function or preventing HTTP handlers from recovering panics and ignoring them.

func Fatalf

func Fatalf(ctx context.Context, format string, args ...interface{})

Fatalf logs to the INFO, WARNING, ERROR, and FATAL logs, including a stack trace of all running goroutines, then calls os.Exit(255). It extracts log tags from the context and logs them along with the given message. Arguments are handled in the manner of fmt.Printf; a newline is appended.

func FatalfDepth

func FatalfDepth(ctx context.Context, depth int, format string, args ...interface{})

FatalfDepth logs to the INFO, WARNING, ERROR, and FATAL logs (offsetting the caller's stack frame by 'depth'), including a stack trace of all running goroutines, then calls os.Exit(255). It extracts log tags from the context and logs them along with the given message. Arguments are handled in the manner of fmt.Printf; a newline is appended.

func FinishEventLog

func FinishEventLog(ctx context.Context)

FinishEventLog closes the event log in the context (see WithEventLog). Concurrent and subsequent calls to record events are allowed.

func Flush

func Flush()

Flush flushes all pending log I/O.

func GetLogReader

func GetLogReader(filename string, restricted bool) (io.ReadCloser, error)

GetLogReader returns a reader for the specified filename. In restricted mode, the filename must be the base name of a file in this process's log directory (this is safe for cases when the filename comes from external sources, such as the admin UI via HTTP). In unrestricted mode any path is allowed, with the added feature that relative paths will be searched in both the current directory and this process's log directory.

func Info

func Info(ctx context.Context, args ...interface{})

Info logs to the INFO log. It extracts log tags from the context and logs them along with the given message. Arguments are handled in the manner of fmt.Print; a newline is appended.

func Infof

func Infof(ctx context.Context, format string, args ...interface{})

Infof logs to the INFO log. It extracts log tags from the context and logs them along with the given message. Arguments are handled in the manner of fmt.Printf; a newline is appended.

func InfofDepth

func InfofDepth(ctx context.Context, depth int, format string, args ...interface{})

InfofDepth logs to the INFO log, offsetting the caller's stack frame by 'depth'. It extracts log tags from the context and logs them along with the given message. Arguments are handled in the manner of fmt.Printf; a newline is appended.

func NewStdLogger

func NewStdLogger(severity Severity) *stdLog.Logger

NewStdLogger creates a *stdLog.Logger that forwards messages to the Google logs for the specified severity.

func SetExitFunc

func SetExitFunc(f func(int))

SetExitFunc allows setting a function that will be called to exit the process when a Fatal message is generated.

func V

func V(level level) bool

V returns true if the logging verbosity is set to the specified level or higher.

func VDepth

func VDepth(level level, depth int) bool

VDepth reports whether verbosity at the call site is at least the requested level.

func VEvent

func VEvent(level level, ctx context.Context, msg string)

VEvent either logs a message to the log files (which also outputs to the active trace or event log) or to the trace/event log alone, depending on whether the specified verbosity level is active.

func VEventf

func VEventf(level level, ctx context.Context, format string, args ...interface{})

VEventf either logs a message to the log files (which also outputs to the active trace or event log) or to the trace/event log alone, depending on whether the specified verbosity level is active.

func Warning

func Warning(ctx context.Context, args ...interface{})

Warning logs to the WARNING and INFO logs. It extracts log tags from the context and logs them along with the given message. Arguments are handled in the manner of fmt.Print; a newline is appended.

func Warningf

func Warningf(ctx context.Context, format string, args ...interface{})

Warningf logs to the WARNING and INFO logs. It extracts log tags from the context and logs them along with the given message. Arguments are handled in the manner of fmt.Printf; a newline is appended.

func WarningfDepth

func WarningfDepth(ctx context.Context, depth int, format string, args ...interface{})

WarningfDepth logs to the WARNING and INFO logs, offsetting the caller's stack frame by 'depth'. It extracts log tags from the context and logs them along with the given message. Arguments are handled in the manner of fmt.Printf; a newline is appended.

func WithEventLog

func WithEventLog(ctx context.Context, family, title string) context.Context

WithEventLog creates and embeds a trace.EventLog in the context, causing future logging and event calls to go to the EventLog. The current context must not have an existing open span.

func WithLogTag

func WithLogTag(ctx context.Context, name string, value interface{}) context.Context

WithLogTag returns a context (derived from the given context) which when used with a logging function results in the given name and value being printed in the message.

The value is stored and passed to fmt.Fprint when the log message is constructed. A fmt.Stringer can be passed which allows the value to be "dynamic".

If the value is nil, just the name shows up.

func WithLogTagInt

func WithLogTagInt(ctx context.Context, name string, value int) context.Context

WithLogTagInt is a variant of WithLogTag that avoids the allocation associated with boxing the value in an interface{}.

func WithLogTagInt64

func WithLogTagInt64(ctx context.Context, name string, value int64) context.Context

WithLogTagInt64 is a variant of WithLogTag that avoids the allocation associated with boxing the value in an interface{}.

func WithLogTagStr

func WithLogTagStr(ctx context.Context, name string, value string) context.Context

WithLogTagStr is a variant of WithLogTag that avoids the allocation associated with boxing the value in an interface{}.

func WithLogTagsFromCtx

func WithLogTagsFromCtx(ctx, fromCtx context.Context) context.Context

WithLogTagsFromCtx returns a context based on ctx with fromCtx's log tags added on.

The result is equivalent to replicating the WithLogTag* calls that were used to obtain fromCtx and applying them to ctx in the same order - but skipping those for which ctx already has a tag with the same name.

func WithNoEventLog

func WithNoEventLog(ctx context.Context) context.Context

WithNoEventLog creates a context which no longer has an embedded event log.

Types

type DynamicIntValue

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

DynamicIntValue is a helper type that allows using a "dynamic" int32 value for a log tag.

func (*DynamicIntValue) Set

func (dv *DynamicIntValue) Set(newVal int64)

Set changes the value returned by String().

func (*DynamicIntValue) String

func (dv *DynamicIntValue) String() string

type Entry

type Entry struct {
	Severity Severity `protobuf:"varint,1,opt,name=severity,proto3,enum=cockroach.util.log.Severity" json:"severity,omitempty"`
	// Nanoseconds since the epoch.
	Time      int64  `protobuf:"varint,2,opt,name=time,proto3" json:"time,omitempty"`
	Goroutine int64  `protobuf:"varint,6,opt,name=goroutine,proto3" json:"goroutine,omitempty"`
	File      string `protobuf:"bytes,3,opt,name=file,proto3" json:"file,omitempty"`
	Line      int64  `protobuf:"varint,4,opt,name=line,proto3" json:"line,omitempty"`
	Message   string `protobuf:"bytes,5,opt,name=message,proto3" json:"message,omitempty"`
}

Entry represents a cockroach structured log entry.

func FetchEntriesFromFiles

func FetchEntriesFromFiles(severity Severity, startTimestamp, endTimestamp int64, maxEntries int,
	pattern *regexp.Regexp) ([]Entry, error)

FetchEntriesFromFiles fetches all available log entries on disk that match the log 'severity' (or worse) and are between the 'startTimestamp' and 'endTimestamp'. It will stop reading new files if the number of entries exceeds 'maxEntries'. Log entries are further filtered by the regexp 'pattern' if provided. The logs entries are returned in reverse chronological order.

func (*Entry) Descriptor

func (*Entry) Descriptor() ([]byte, []int)

func (*Entry) Marshal

func (m *Entry) Marshal() (data []byte, err error)

func (*Entry) MarshalTo

func (m *Entry) MarshalTo(data []byte) (int, error)

func (*Entry) ProtoMessage

func (*Entry) ProtoMessage()

func (*Entry) Reset

func (m *Entry) Reset()

func (*Entry) Size

func (m *Entry) Size() (n int)

func (*Entry) String

func (m *Entry) String() string

func (*Entry) Unmarshal

func (m *Entry) Unmarshal(data []byte) error

type EntryDecoder

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

EntryDecoder reads successive encoded log entries from the input buffer. Each entry is preceded by a single big-ending uint32 describing the next entry's length.

func NewEntryDecoder

func NewEntryDecoder(in io.Reader) *EntryDecoder

NewEntryDecoder creates a new instance of EntryDecoder.

func (*EntryDecoder) Decode

func (d *EntryDecoder) Decode(entry *Entry) error

Decode decodes the next log entry into the provided protobuf message.

type FileDetails

type FileDetails struct {
	Program  string   `protobuf:"bytes,1,opt,name=program,proto3" json:"program,omitempty"`
	Host     string   `protobuf:"bytes,2,opt,name=host,proto3" json:"host,omitempty"`
	UserName string   `protobuf:"bytes,3,opt,name=user_name,json=userName,proto3" json:"user_name,omitempty"`
	Severity Severity `protobuf:"varint,4,opt,name=severity,proto3,enum=cockroach.util.log.Severity" json:"severity,omitempty"`
	Time     int64    `protobuf:"varint,5,opt,name=time,proto3" json:"time,omitempty"`
	PID      int64    `protobuf:"varint,6,opt,name=pid,proto3" json:"pid,omitempty"`
}

A FileDetails holds all of the particulars that can be parsed by the name of a log file.

func (*FileDetails) Descriptor

func (*FileDetails) Descriptor() ([]byte, []int)

func (*FileDetails) Marshal

func (m *FileDetails) Marshal() (data []byte, err error)

func (*FileDetails) MarshalTo

func (m *FileDetails) MarshalTo(data []byte) (int, error)

func (*FileDetails) ProtoMessage

func (*FileDetails) ProtoMessage()

func (*FileDetails) Reset

func (m *FileDetails) Reset()

func (*FileDetails) Size

func (m *FileDetails) Size() (n int)

func (*FileDetails) String

func (m *FileDetails) String() string

func (*FileDetails) Unmarshal

func (m *FileDetails) Unmarshal(data []byte) error

type FileInfo

type FileInfo struct {
	Name         string      `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
	SizeBytes    int64       `protobuf:"varint,2,opt,name=size_bytes,json=sizeBytes,proto3" json:"size_bytes,omitempty"`
	ModTimeNanos int64       `protobuf:"varint,3,opt,name=mod_time_nanos,json=modTimeNanos,proto3" json:"mod_time_nanos,omitempty"`
	Details      FileDetails `protobuf:"bytes,4,opt,name=details" json:"details"`
}

func ListLogFiles

func ListLogFiles() ([]FileInfo, error)

ListLogFiles returns a slice of FileInfo structs for each log file on the local node, in any of the configured log directories.

func (*FileInfo) Descriptor

func (*FileInfo) Descriptor() ([]byte, []int)

func (*FileInfo) Marshal

func (m *FileInfo) Marshal() (data []byte, err error)

func (*FileInfo) MarshalTo

func (m *FileInfo) MarshalTo(data []byte) (int, error)

func (*FileInfo) ProtoMessage

func (*FileInfo) ProtoMessage()

func (*FileInfo) Reset

func (m *FileInfo) Reset()

func (*FileInfo) Size

func (m *FileInfo) Size() (n int)

func (*FileInfo) String

func (m *FileInfo) String() string

func (*FileInfo) Unmarshal

func (m *FileInfo) Unmarshal(data []byte) error

type Severity

type Severity int32
const (
	Severity_UNKNOWN Severity = 0
	Severity_INFO    Severity = 1
	Severity_WARNING Severity = 2
	Severity_ERROR   Severity = 3
	Severity_FATAL   Severity = 4
	// NONE is the end sentinel. It is never used in pracice, and must be
	// renumbered to remain at the end if new variants are added.
	Severity_NONE Severity = 5
)

func SeverityByName

func SeverityByName(s string) (Severity, bool)

SeverityByName attempts to parse the passed in string into a severity. (i.e. ERROR, INFO). If it succeeds, the returned bool is set to true.

func (Severity) EnumDescriptor

func (Severity) EnumDescriptor() ([]byte, []int)

func (*Severity) Name

func (s *Severity) Name() string

Name returns the string representation of the severity (i.e. ERROR, INFO).

func (*Severity) Set

func (s *Severity) Set(value string) error

Set is part of the flag.Value interface.

func (Severity) String

func (x Severity) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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