log

package module
v0.0.0-...-01ae986 Latest Latest
Warning

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

Go to latest
Published: May 22, 2018 License: Apache-2.0 Imports: 11 Imported by: 0

README

LOG
===

Leveled execution logs for Go; minimal interface with fine grained control
(file level, sub-package level, severity) for log evaluation.

This is an amalgamation of ideas from multiple logger implementations, notably:
  - google/glog
  - go-kit/kit/log
  - upspin/log
  - cockroachdb/pkg/log

Intended top-level usage:

  $ <binary-name> -help
  Usage of <binary-name>:
    -log-dir string
          Write log files in this directory.
    -log-to-stderr
          Log to standard error.
    -log-level (info|debug|warn|error)
          Log level for logs emitted (global, can be overrode using -log-filter).
    -log-filter value
          Comma-separated list of pattern:level settings for file-filtered logging.
    -log-backtrace-at value
          Comma-separated list of filename:N settings, when any logging statement at
          the specified locations are executed, a stack trace will be emitted.

  $ <binary-name> -log-level info \
                  -log-dir /path/to/dir \
                  -log-to-stderr \
                  -log-filter f.go:warn,g/h/*.go:debug \
                  -log-backtrace-at y.go:42

The flags (or some variation thereof) will have to be provided/registered by
the library user, this library simply provides the hooks the user can then use
to configure the logger as needed. These hooks can be invoked at runtime (in
fact, we explicitly avoid init time hooks and global loggers). What this means
is that if needed, a running service could opt-in to provide open endpoints
to accept logger reconfigurations (via RPCs or otherwise).

Assuming <binary-name> from above allows for an authenticated RPC from another
helper binary:

  $ <binary-name>-debugger -help
  Usage of <binary-name>-debugger:
    -addr host:port
          Server address in form of host:port for running instance of
          <binary-name> that is to be configured.
    -log-dir string
          Configure server to write log files in this directory.
    -log-to-stderr
          Configure server to log to standard error.
    -log-level (info|debug|warn|error|fatal)
          Configure server to log at specified level.
    -log-filter value
          Comma-separated list of pattern:N settings for file-filtered logging
          to configure server to apply.
    -log-backtrace-at value
          Comma-separated list of filename:N settings, when any logging statement at
          the specified locations are executed, a stack trace will be emitted.

  $ <binary-name>-debugger -addr <host>:<port> \
                           -log-level debug \
                           -log-dir /path/to/another/dir \
                           -log-filter x.go:debug \
                           -log-backtrace-at y.go:42

Documentation

Overview

Package log implements leveled execution logs for go. The library provides hooks such that the following top-level usage is made possible:

$ <binary-name> -help
Usage of <binary-name>:
  -log-dir string
        Write log files in this directory.
  -log-to-stderr
        Log to standard error.
  -log-level (info|debug|warn|error)
        Log level for logs emitted (global, can be overrode using -log-filter).
  -log-filter value
        Comma-separated list of pattern:level settings for file-filtered logging.
  -log-backtrace-at value
        Comma-separated list of filename:N settings, when any logging statement at
        the specified locations are executed, a stack trace will be emitted.

$ <binary-name> -log-level info \
                -log-dir /path/to/dir \
                -log-to-stderr \
                -log-filter f.go:warn,g/h/*.go:debug \
                -log-backtrace-at y.go:42

These hooks can be invoked at runtime, what this means is that if needed, a running service could opt-in to provide open endpoints to accept logger reconfigurations (via RPCs or otherwise).

Basic example:

import "github.com/irfansharif/log"

...

logger := log.New()
logger.Info("hello, world")

The logger can be be configured to be safe for concurrent use, output to rotating logs, log with specific formatted headers, etc. using variadic options during initialization. An example of the above:

writer := os.Stderr
writer = log.SynchronizedWriter(writer)
writer = log.MultiWriter(writer,
                log.LogRotationWriter("/logs", 50 << 20 /* 50 MiB */))

logf := log.Lmode | log.Ldate | log.Ltime | log.Llongfile

logger.New(log.Writer(writer), log.Flags(logf))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultWriter

func DefaultWriter() io.Writer

DefaultWriter returns a default os.Stderr writer that is safe for concurrent use.

func Flags

func Flags(flags Flag) option

Flags configures the header format for all logs emitted by a Logger instance.

func GetTracePoint

func GetTracePoint(tp string) (tpenabled bool)

GetTracePoint checks if the corresponding tracepoint is enabled.

func LogRotationWriter

func LogRotationWriter(dirname string, sizeThreshold int) io.Writer

LogRotationWriter returns an io.Writer that internally operates off the specified directory where writes are written out to rotating files, thresholded at the specified size in bytes. Within the directory a symlink is generated pointing to the most recently created log file.

For the case where the size of the write exceeds the provided threshold size (which is probably indicative of an improperly configured threshold), we write it out to a single file. This is the only instance where the log file size may exceed the specified size limit.

func MultiWriter

func MultiWriter(w io.Writer, ws ...io.Writer) io.Writer

MultiWriter multiplexes writes to multiple io.Writers.

func ResetFileLogMode

func ResetFileLogMode(fname string)

ResetFileLogMode resets the log mode for the provided filename. Subsequent logging statements within the file get filtered as per the global log mode.

func ResetTracePoint

func ResetTracePoint(tp string)

ResetTracePoint resets the provided tracepoint so that a backtraces are no longer emitted when the specified logging statement is executed. See comment for SetTracePoint for what a tracepoint is.

func SetFileLogMode

func SetFileLogMode(fname string, m Mode)

SetFileLogMode sets the log mode for the provided filename. Subsequent logging statements within the file get filtered accordingly.

func SetGlobalLogMode

func SetGlobalLogMode(m Mode)

SetGlobalLogMode sets the global log mode to the one specified. Logging outside what's included in the mode is thereby suppressed.

func SetTracePoint

func SetTracePoint(tp string)

SetTracePoint enables the provided tracepoint. A tracepoint is of the form filename.go:line-number (compiles to [\w]+.go:[\d]+) corresponding to the position of a logging statement that once enabled, emits a backtrace when the logging statement is executed. The specified tracepoint is agnostic to the mode, i.e. Logger.{Info|Warn|Error|Fatal|Debug}{,f}, used at the line.

func SkipBasePath

func SkipBasePath(path ...string) option

SkipBasePath allows for log.Llongfile to only write out filepaths relative to project root. For example:

I180419 06:33:04.606396 main.go:89] from main!
I180419 06:33:04.606420 pkg/logger.go:6] from pkg!
I180419 06:33:04.606426 pkg/subpkg/logger.go:6] from pkg/subpkg!

Instead of:

I180419 06:36:26.554520 [...]/log/cmd/logger/main.go:89] from main!
I180419 06:36:26.554555 [...]/log/cmd/logger/pkg/logger.go:6] from pkg!
I180419 06:36:26.554566 [...]/log/cmd/logger/pkg/subpkg/logger.go:6] from pkg/subpkg!

Use SkipBasePath() with no arguments if calling from the root of the project/repository (think top level main.go). Barring that, passing in the fully qualified path of the project base strips out the corresponding prefix from subsequent log statements.

func SynchronizedWriter

func SynchronizedWriter(w io.Writer) io.Writer

SynchronizedWriter wraps an io.Writer with a mutex for concurrent access.

func Writer

func Writer(w io.Writer) option

Writer configures a Logger instance with the specified io.Writer.

Types

type Flag

type Flag int
const (
	Ldate         Flag = 1 << iota // The date in the local time zone: 180419 (yymmdd)
	Ltime                          // The time in the local time zone: 01:23:23
	Lmicroseconds                  // Microsecond resolution: 01:23:23.123123, assumes Ltime
	Llongfile                      // Fully qualified file path and line number: /a/b/c/d.go:23
	Lshortfile                     // File name and line number: d.go:23. overrides Llongfile
	LUTC                           // If Ldate or Ltime is set, use UTC instead of local time zone
	Lmode                          // If Lmode is set, each line is prefixed by statement log mode

	// Default values for the logger, produces:
	//   I180419 06:33:04.606396 fname.go:42 message
	LstdFlags = Lmode | Ldate | Ltime | Lmicroseconds | LUTC | Lshortfile
)

These flags define which text to prefix to each log entry generated by the Logger.

type Logger

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

Logger is the concrete logger type. It writes out logs to the specified io.Writer, with the header format determined by the flags set.

func New

func New(options ...option) *Logger

New returns a new Logger, configured with the provided options, if any.

func (*Logger) Debug

func (l *Logger) Debug(v ...interface{})

Debug logs to the DEBUG log. Arguments are handled in the manner of fmt.Println; a newline is appended at the end.

func (*Logger) Debugf

func (l *Logger) Debugf(format string, v ...interface{})

Debugf logs to the DEBUG log. Arguments are handled in the manner of fmt.Printf; a newline is appended at the end.

func (*Logger) Error

func (l *Logger) Error(v ...interface{})

Error logs to the ERROR log. Arguments are handled in the manner of fmt.Println; a newline is appended at the end.

func (*Logger) Errorf

func (l *Logger) Errorf(format string, v ...interface{})

Errorf logs to the ERROR log. Arguments are handled in the manner of fmt.Printf; a newline is appended at the end.

func (*Logger) Fatal

func (l *Logger) Fatal(v ...interface{})

Fatal logs to the FATAL log. Arguments are handled in the manner of fmt.Println; a newline is appended at the end.

TODO(irfansharif): Including a stack trace of all running goroutines, then calls os.Exit(255).

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, v ...interface{})

Fatalf logs to the FATAL log. Arguments are handled in the manner of fmt.Printf; a newline is appended at the end.

TODO(irfansharif): Including a stack trace of all running goroutines, then calls os.Exit(255).

func (*Logger) Info

func (l *Logger) Info(v ...interface{})

Info logs to the INFO log. Arguments are handled in the manner of fmt.Println; a newline is appended at the end.

func (*Logger) Infof

func (l *Logger) Infof(format string, v ...interface{})

Infof logs to the INFO log. Arguments are handled in the manner of fmt.Printf; a newline is appended at the end.

func (*Logger) Warn

func (l *Logger) Warn(v ...interface{})

Warn logs to the WARN log. Arguments are handled in the manner of fmt.Println; a newline is appended at the end.

func (*Logger) Warnf

func (l *Logger) Warnf(format string, v ...interface{})

Warnf logs to the WARN log. Arguments are handled in the manner of fmt.Printf; a newline is appended at the end.

type Mode

type Mode int

TODO(irfansharif): Comment, explain modal logging concept.

const (
	InfoMode Mode = 1 << iota
	WarnMode
	ErrorMode
	FatalMode
	DebugMode

	// The zero-value of DisableMode can also be used to check if modes
	// intersect, i.e.  (lmode&gmode) != DisabledMode checks if the local
	// logger mode is filtered through by the global mode.
	DisabledMode = 0
	DefaultMode  = InfoMode | WarnMode | ErrorMode
)

func GetFileLogMode

func GetFileLogMode(fname string) (m Mode, ok bool)

GetFileLogMode gets the log mode for the specified file.

func GetGlobalLogMode

func GetGlobalLogMode() Mode

GetGlobalLogMode gets the currently set global log mode.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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