Documentation
¶
Index ¶
- Constants
- Variables
- func DirSet() bool
- func DisableTracebacks() func()
- func Error(ctx context.Context, args ...interface{})
- func Errorf(ctx context.Context, format string, args ...interface{})
- func ErrorfDepth(ctx context.Context, depth int, format string, args ...interface{})
- func ExpensiveLogEnabled(ctx context.Context, level int32) bool
- func Fatal(ctx context.Context, args ...interface{})
- func FatalChan() <-chan struct{}
- func FatalOnPanic()
- func Fatalf(ctx context.Context, format string, args ...interface{})
- func FatalfDepth(ctx context.Context, depth int, format string, args ...interface{})
- func Flush()
- func FormatTags(ctx context.Context, buf *strings.Builder) bool
- func GetLogReader(filename string, restricted bool) (io.ReadCloser, error)
- func Info(ctx context.Context, args ...interface{})
- func InfoDepth(ctx context.Context, depth int, args ...interface{})
- func Infof(ctx context.Context, format string, args ...interface{})
- func InfofDepth(ctx context.Context, depth int, format string, args ...interface{})
- func Intercept(ctx context.Context, f InterceptorFn)
- func LoggingToStderr(s Severity) bool
- func MakeMessage(ctx context.Context, format string, args []interface{}) string
- func NewStdLogger(severity Severity) *stdLog.Logger
- func ReportPanic(ctx context.Context, r interface{})
- func ResetExitFunc()
- func SetClusterID(clusterID string)
- func SetExitFunc(hideStack bool, f func(int))
- func SetSync(sync bool)
- func SetVModule(value string) error
- func Shout(ctx context.Context, sev Severity, args ...interface{})
- func StartGCDaemon(ctx context.Context)
- func V(level int32) bool
- func VDepth(l int32, depth int) bool
- func Warning(ctx context.Context, args ...interface{})
- func Warningf(ctx context.Context, format string, args ...interface{})
- func WarningfDepth(ctx context.Context, depth int, format string, args ...interface{})
- type DirName
- type Entry
- type EntryDecoder
- type FileDetails
- type FileInfo
- type InterceptorFn
- type SecondaryLogger
- type Severity
- type TestLogScope
Constants ¶
const FileNamePattern = `(?P<program>[^/.]+)\.(?P<host>[^/\.]+)\.` +
`(?P<user>[^/\.]+)\.(?P<ts>[^/\.]+)\.(?P<pid>\d+)\.log`
FileNamePattern matches log files to avoid exposing non-log files accidentally and it splits the details of the filename into groups for easy parsing. The log file format is
{program}.{host}.{username}.{timestamp}.{pid}.log cockroach.Brams-MacBook-Pro.bram.2015-06-09T16-10-48Z.30209.log
All underscore in process, host and username are escaped to double underscores and all periods are escaped to an underscore. For compatibility with Windows filenames, all colons from the timestamp (RFC3339) are converted from underscores (see FileTimePattern). Note this pattern is unanchored and becomes anchored through its use in LogFilePattern.
const FilePattern = "^(?:.*/)?" + FileNamePattern + "$"
FilePattern matches log file paths.
const FileTimeFormat = "2006-01-02T15_04_05Z07:00"
FileTimeFormat is RFC3339 with the colons replaced with underscores. It is the format used for timestamps in log file names. This removal of colons creates log files safe for Windows file systems.
const MessageTimeFormat = "060102 15:04:05.999999"
MessageTimeFormat is the format of the timestamp in log message headers as used in time.Parse and time.Format.
Variables ¶
var LogFileMaxSize int64 = 10 << 20 // 10MiB
LogFileMaxSize is the maximum size of a log file in bytes.
var LogFilesCombinedMaxSize = LogFileMaxSize * 10 // 100MiB
LogFilesCombinedMaxSize is the maximum total size in bytes for log files. Note that this is only checked when log files are created, so the total size of log files per severity might temporarily be up to LogFileMaxSize larger.
var OrigStderr = func() *os.File { fd, err := dupFD(os.Stderr.Fd()) if err != nil { panic(err) } return os.NewFile(fd, os.Stderr.Name()) }()
OrigStderr points to the original stderr stream.
var Severity_name = map[int32]string{
0: "UNKNOWN",
1: "INFO",
2: "WARNING",
3: "ERROR",
4: "FATAL",
5: "NONE",
6: "DEFAULT",
}
var Severity_value = map[string]int32{
"UNKNOWN": 0,
"INFO": 1,
"WARNING": 2,
"ERROR": 3,
"FATAL": 4,
"NONE": 5,
"DEFAULT": 6,
}
Functions ¶
func DirSet ¶
func DirSet() bool
DirSet returns true of the log directory has been changed from its default.
func DisableTracebacks ¶
func DisableTracebacks() func()
DisableTracebacks turns off tracebacks for log.Fatals. Returns a function that sets the traceback settings back to where they were. Only intended for use by tests.
func Error ¶
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 ¶
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 ¶
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 ExpensiveLogEnabled ¶
ExpensiveLogEnabled is used to test whether effort should be used to produce log messages whose construction has a measurable cost. It returns true if either the current context is recording the trace, or if the caller's verbosity is above level.
NOTE: This doesn't take into consideration whether tracing is generally enabled or whether a trace.EventLog or a trace.Trace (i.e. sp.netTr) is attached to ctx. In particular, if some OpenTracing collection is enabled (e.g. LightStep), that, by itself, does NOT cause the expensive messages to be enabled. "SET tracing" and friends, on the other hand, does cause these messages to be enabled, as it shows that a user has expressed particular interest in a trace.
Usage:
if ExpensiveLogEnabled(ctx, 2) { msg := constructExpensiveMessage() log.VEventf(ctx, 2, msg) }
func Fatal ¶
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 FatalChan ¶
func FatalChan() <-chan struct{}
FatalChan is closed when Fatal is called. This can be used to make the process stop handling requests while the final log messages and crash report are being written.
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 ¶
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 ¶
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 FormatTags ¶
FormatTags appends the tags to a strings.Builder. If there are no tags, returns false.
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, relative to the current directory, with the added feature that simple (base name) file names will be searched in this process's log directory if not found in the current directory.
func Info ¶
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 InfoDepth ¶
InfoDepth 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.Print; a newline is appended.
func Infof ¶
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 ¶
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 Intercept ¶
func Intercept(ctx context.Context, f InterceptorFn)
Intercept diverts log traffic to the given function `f`. When `f` is not nil, the logging package begins operating at full verbosity (i.e. `V(n) == true` for all `n`) but nothing will be printed to the logs. Instead, `f` is invoked for each log entry.
To end log interception, invoke `Intercept()` with `f == nil`. Note that interception does not terminate atomically, that is, the originally supplied callback may still be invoked after a call to `Intercept` with `f == nil`.
func LoggingToStderr ¶
LoggingToStderr returns true if log messages of the given severity are visible on stderr.
func MakeMessage ¶
MakeMessage creates a structured log entry.
func NewStdLogger ¶
NewStdLogger creates a *stdLog.Logger that forwards messages to the CockroachDB logs with the specified severity.
func ReportPanic ¶
ReportPanic reports a panic has occurred on the real stderr.
func SetClusterID ¶
func SetClusterID(clusterID string)
SetClusterID stores the Cluster ID for further reference.
func SetExitFunc ¶
SetExitFunc allows setting a function that will be called to exit the process when a Fatal message is generated. The supplied bool, if true, suppresses the stack trace, which is useful for test callers wishing to keep the logs reasonably clean.
Call with a nil function to undo.
func SetVModule ¶
SetVModule alters the vmodule logging level to the passed in value.
func Shout ¶
Shout logs to the specified severity's log, and also to the real stderr if logging is currently redirected to a file.
func StartGCDaemon ¶
StartGCDaemon starts the log file GC -- this must be called after command-line parsing has completed so that no data is lost when the user configures larger max sizes than the defaults.
The logger's GC daemon stops when the provided context is canceled.
func V ¶
V returns true if the logging verbosity is set to the specified level or higher.
See also ExpensiveLogEnabled().
TODO(andrei): Audit uses of V() and see which ones should actually use the newer ExpensiveLogEnabled().
func Warning ¶
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 ¶
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 ¶
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.
Types ¶
type DirName ¶
DirName overrides (if non-empty) the choice of directory in which to write logs. See createLogDirs for the full list of possible destinations. Note that the default is to log to stderr independent of this setting. See --logtostderr.
type Entry ¶
type Entry struct { Severity Severity // Nanoseconds since the epoch. Time int64 Goroutine int64 File string Line int64 Message string }
Entry represents a cockroach structured log entry.
func FetchEntriesFromFiles ¶
func FetchEntriesFromFiles( startTimestamp, endTimestamp int64, maxEntries int, pattern *regexp.Regexp, ) ([]Entry, error)
FetchEntriesFromFiles fetches all available log entries on disk that 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.
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 ¶
A FileDetails holds all of the particulars that can be parsed by the name of a log file.
func ParseLogFilename ¶
func ParseLogFilename(filename string) (FileDetails, error)
ParseLogFilename parses a filename into FileDetails if it matches the pattern for log files. If the filename does not match the log file pattern, an error is returned.
type FileInfo ¶
type FileInfo struct { Name string SizeBytes int64 ModTimeNanos int64 Details FileDetails }
func ListLogFiles ¶
ListLogFiles returns a slice of FileInfo structs for each log file on the local node, in any of the configured log directories.
func MakeFileInfo ¶
func MakeFileInfo(details FileDetails, info os.FileInfo) FileInfo
MakeFileInfo constructs a FileInfo from FileDetails and os.FileInfo.
type InterceptorFn ¶
type InterceptorFn func(entry Entry)
InterceptorFn is the type of function accepted by Intercept().
type SecondaryLogger ¶
type SecondaryLogger struct {
// contains filtered or unexported fields
}
SecondaryLogger represents a secondary / auxiliary logging channel whose logging events go to a different file than the main logging facility.
func NewSecondaryLogger ¶
func NewSecondaryLogger( ctx context.Context, dirName *DirName, fileNamePrefix string, enableGc, forceSyncWrites bool, ) *SecondaryLogger
NewSecondaryLogger creates a secondary logger.
The given directory name can be either nil or empty, in which case the global logger's own dirName is used; or non-nil and non-empty, in which case it specifies the directory for that new logger.
The logger's GC daemon stops when the provided context is canceled.
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 used to specify when no messages // should be printed to the log file or stderr. Severity_NONE Severity = 5 // DEFAULT is the end sentinel. It is used during command-line // handling to indicate that another value should be replaced instead // (depending on which command is being run); see cli/flags.go for // details. Severity_DEFAULT Severity = 6 )
func SeverityByName ¶
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.
type TestLogScope ¶
type TestLogScope struct {
// contains filtered or unexported fields
}
TestLogScope represents the lifetime of a logging output. It ensures that the log files are stored in a directory specific to a test, and asserts that logging output is not written to this directory beyond the lifetime of the scope.
func Scope ¶
func Scope(t tShim) *TestLogScope
Scope creates a TestLogScope which corresponds to the lifetime of a logging directory. The logging directory is named after the calling test. It also disables logging to stderr.
func ScopeWithoutShowLogs ¶
func ScopeWithoutShowLogs(t tShim) *TestLogScope
ScopeWithoutShowLogs ignores the -show-logs flag and should be used for tests that require the logs go to files.
func (*TestLogScope) Close ¶
func (l *TestLogScope) Close(t tShim)
Close cleans up a TestLogScope. The directory and its contents are deleted, unless the test has failed and the directory is non-empty.