conlog

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: May 23, 2019 License: MIT Imports: 11 Imported by: 0

README

go-conlog

Conlog is a golang logging package heavily leveraged from the popular logrus package. It differs from logrus in that it is optimized for console output rather than for use with log files. Like logrus, conlog is completely API compatible with the standard library logger.

Build Status GoDoc

Features

  • Level logging -- only log messages at at or below one of the following levels: Panic, Fatal, Error, Warning, Info, or Debug.
  • Optionally display log levels in the log message.
  • Optionally display wallclock or elapsed time in log messages.
  • Optional colorized log level when output is to a TTY.
  • Print*-style message logging that ignores the log level which can be optionally suppressed for verbose/non-verbose output.
  • Log a message to multiple logs with one call.

Documentation

Documentation can be found at GoDoc

Installation

Install conlog using the "go get" command:

$ go get -u github.com/apatters/go-conlog

The Go distribution is conlog's only dependency.

Examples

Basic operation
package main

import (
	"fmt"
	"io/ioutil"
	"os"

	log "github.com/apatters/go-conlog"
)

func main() {
	// Messages are output/not output depending on log level. The
	// log level (in ascending order are:
	//
	// PanicLevel
	// FatalLevel
	// ErrorLevel
	// WarnLevel
	// InfoLevel
	// DebugLevel
	log.SetLevel(log.DebugLevel)
	formatter := log.NewStdFormatter()
	formatter.Options.LogLevelFmt = log.LogLevelFormatLongTitle
	log.SetFormatter(formatter)
	// log.Panic("This is a panic message.")
	// log.Fatal("This is a fatal message.")
	log.Error("This is an error message.")
	log.Warn("This is a warning message.")
	log.Warning("This is also a warning message.")
	log.Info("This is an info message.")
	log.Debug("This is a debug message.")

	// The default log level is Level.Info. You can set a
	// different log level using SetLevel.
	log.SetLevel(log.WarnLevel)
	formatter = log.NewStdFormatter()
	formatter.Options.LogLevelFmt = log.LogLevelFormatShort
	log.SetFormatter(formatter)
	log.Info("This message is above the log level so is not output.")
	log.Warning("This message is at the log level so it is output.")
	log.Error("This message is below the log level so it too is output.")

	// There are three forms of output functions for each log
	// level corresponding to the fmt.Print* functions. So the
	// log.Error* output functions have a log.Error(),
	// Log.Errorln, and log.Errorf variations corresponding to
	// fmt.Print(), fmt.Println, and fmt.Printf(). They process
	// parameters in the same way as their fmt counterparts,
	// except that a newline is always output.
	log.SetLevel(log.DebugLevel)
	log.Infoln("Print a number with a newline:", 4)
	log.Info("Print a number also with a newline (note we have to add a space): ", 4)
	log.Infof("Print a formatted number with a newline: %d", 4)

	// Output is send to stderr for log levels of PanicLevel,
	// FatalLevel, and ErrorLevel. Output is sent to stdout for
	// log levels above ErrorLevel. You can change this behavior
	// by setting the Writers in the logger. For
	// example, if we want all output to go to stdout, use:
	log.SetErrorOutput(os.Stdout)
	log.Info("This message is going to stdout.")
	log.Error("This message is now also going to stdout.")

	// We can send output to any Writer. For example, to send
	// output for all levels to a file, we can use:
	logFile, _ := ioutil.TempFile("", "mylogfile-")
	defer logFile.Close()
	log.SetOutput(logFile)
	log.SetErrorOutput(logFile)
	log.Info("This message is going to the logfile.")
	log.Error("This message is also going to the logfile.")
	// Dump to stdout so we can see the results.
	contents, _ := ioutil.ReadFile(logFile.Name())
	fmt.Printf("%s", contents)

	// There are a set of Print* output methods that behave
	// exactly like the corresponding fmt.Print* functions except
	// that output goes to the log.Out writer and output can be
	// suppressed using the SetPrintEnabled() method (enabled by
	// default). Note, Print methods are not in any way governed
	// by the log level.
	//
	// Command-line programs should generally use these Print*
	// functions in favor of the corresponding fmt versions if
	// using this logging system.
	//
	// Unlike the log level output methods, the Print and Printf
	// methods do not output a trailing newline.
	log.SetOutput(os.Stdout)       // Restore default Output writer.
	log.SetErrorOutput(os.Stderr)  // Restore default ErrorOutput writer.
	log.Println("Print a number with an implicit newline:", 4.0)
	log.Print("Print a number with an added newline (note we have to add a space): ", 4.0, "\n")
	log.Printf("Print a formatted number with an added newline: %f\n", 4.0)

	// We can suppress Print* output using the SetPrintEnabled
	// method. This feature can be useful for programs that have a
	// --verbose option. You can disable Print* output by default
	// and then enable it when the verbose flag it set.
	log.SetPrintEnabled(false)
	fmt.Printf("Printing enabled: %t\n", log.GetPrintEnabled())
	log.Printf("This print message is suppressed.\n")
	log.SetPrintEnabled(true)
	fmt.Printf("Printing enabled: %t\n", log.GetPrintEnabled())
	log.Printf("Print message are no longer suppressed.\n")
}

The above example program outputs:

Error This is an error message.
Warning This is a warning message.
Warning This is also a warning message.
Info This is an info message.
Debug This is a debug message.
WARN This message is at the log level so it is output.
ERRO This message is below the log level so it too is output.
INFO Print a number with a newline: 4
INFO Print a number also with a newline (note we have to add a space): 4
INFO Print a formatted number with a newline: 4
INFO This message is going to stdout.
ERRO This message is now also going to stdout.
INFO This message is going to the logfile.
ERRO This message is also going to the logfile.
Print a number with an implicit newline: 4
Print a number with an added newline (note we have to add a space): 4
Print a formatted number with an added newline: 4.000000
Printing enabled: false
Printing enabled: true
Print message are no longer suppressed.
Using the formatter

The formatter is used to modify the output of the message. It can be used to add a leader to the message which might include various forms of the the log level, and/or a wall or elapsed time stamp.

package main

import (
	"time"

	log "github.com/apatters/go-conlog"
)

func main() {
	// Basic logging using the default formatter.
	log.Info("This is an info message without a leader.")
	log.Warning("This is a warning message without a leader.")
	log.Error("This is an error message without a leader.")

	// Basic logging showing log level leaders.
	formatter := log.NewStdFormatter()
	formatter.Options.LogLevelFmt = log.LogLevelFormatLongTitle
	log.SetFormatter(formatter)
	log.Info("This is an info message with a leader.")
	log.Warning("This is a warning message with a leader.")
	log.Error("This is an error message with a leader.")

	// The leader can be colorized if going to a tty. If output is
	// going to a file or pipe, no color is used.
	log.SetLevel(log.DebugLevel)
	formatter = log.NewStdFormatter()
	formatter.Options.LogLevelFmt = log.LogLevelFormatLongTitle
	formatter.Options.ShowLogLevelColors = true
	log.SetFormatter(formatter)
	log.Debug("Debug messages are blue.")
	log.Info("Info messages are green.")
	log.Warn("Warning messages are yellow.")
	log.Error("Error messages are red.")

	// You can show the traditional logrus log levels using the
	// formatter LogLevelFormatShort option:
	formatter = log.NewStdFormatter()
	formatter.Options.LogLevelFmt = log.LogLevelFormatShort
	log.SetFormatter(formatter)
	log.Debug("Debug message with a short leader.")
	log.Info("Info message with a short leader.")
	log.Warn("Warning message with a short leader.")
	log.Error("Error message with a short leader.")

	// You can show long-form log levels in lower-case using the
	// formatter LogLevelFormatLongLower option:
	formatter = log.NewStdFormatter()
	formatter.Options.LogLevelFmt = log.LogLevelFormatLongLower
	log.SetFormatter(formatter)
	log.Debug("Debug message with a long, lowercase leader.")
	log.Info("Info message with a long, lowercase leader.")
	log.Warn("Warning message with a long, lowercase leader.")
	log.Error("Error message with a long, lowercase leader.")

	// You can show time stamps in wall clock time with various
	// formats.
	formatter = log.NewStdFormatter()
	formatter.Options.TimestampType = log.TimestampTypeWall
	formatter.Options.LogLevelFmt = log.LogLevelFormatLongTitle
	log.SetFormatter(formatter)
	log.Info("Info message with wall clock time (default RFC3339 format).")
	formatter = log.NewStdFormatter()
	formatter.Options.TimestampType = log.TimestampTypeWall
	formatter.Options.LogLevelFmt = log.LogLevelFormatLongTitle
	formatter.Options.WallclockTimestampFmt = time.ANSIC
	log.SetFormatter(formatter)
	log.Info("Info message with wall clock time (ANSIC format).")
	formatter = log.NewStdFormatter()
	formatter.Options.TimestampType = log.TimestampTypeWall
	formatter.Options.LogLevelFmt = log.LogLevelFormatLongTitle
	formatter.Options.WallclockTimestampFmt = "Jan _2 15:04:05"
	log.SetFormatter(formatter)
	log.Info("Info message with wall clock time (custom format).")

	// You can show time stamps with elapsed time and in various
	// formats.
	formatter = log.NewStdFormatter()
	formatter.Options.TimestampType = log.TimestampTypeElapsed
	formatter.Options.LogLevelFmt = log.LogLevelFormatLongTitle
	log.SetFormatter(formatter)
	log.Info("Info message with elapsed time (start).")
	time.Sleep(time.Second)
	log.Info("Info message with elapsed time (wait one second).")
	formatter = log.NewStdFormatter()
	formatter.Options.TimestampType = log.TimestampTypeElapsed
	formatter.Options.LogLevelFmt = log.LogLevelFormatLongTitle
	formatter.Options.ElapsedTimestampFmt = "%02d"
	log.SetFormatter(formatter)
	log.Info("Info message with elapsed time with custom format.")
}

The above example program outputs:

Formatter example

Logging fatal errors and panics

The Fatal* and Panic* methods are used to make logging the output of fatal conditions consistent with the rest of the conlog logging system. These methods should be only be used in a "main" package and never be buried in other packages (you should be returning errors there instead).

package main

import (
	log "github.com/apatters/go-conlog"
)

// The *Fatal* routines use a panic/recover mechanism to exit with a
// specific exit code. This mechanism requires that we call the
// HandleExit function as the last function in main() if any Fatal*
// method is used. This is usually best done by creating a "deferred"
// call at the beginning of main() before any other deferred calls.

// We define an exit "wrapper" to be called in main if we want to
// explicitly exit. We do not have to call this sort of function to
// fall-through exit (with exit code 0) out of main(). You should not
// call this sort of function outside the main package.
func exit(code int) {
	panic(log.Exit{code})
}

func main() {
	// The exit routines use a panic/recover mechanism to exit
	// with a specific exit code. We need to call the recovery
	// routine in a defer as the first defer in main() so that it
	// gets called last.
	defer log.HandleExit()

	var err error

	// The Fatalln, Fatal, and Fatalf methods output a message and
	// exit with exit code 1. These calls append a newline to the
	// message.
	if err != nil {
		log.Fatalln("Fatal message exiting with exit code (note we have added a space): ", 1)
	}
	if err != nil {
		log.Fatal("Fatal message exiting with exit code:", 1)
	}
	if err != nil {
		log.Fatalf("Fatal message exiting with exit code %d", 1)
	}

	// The Fatal*WithExitCode methods work like Fatalln, Fatal,
	// and Fatalf except that you can specify the exit code to
	// use.
	if err != nil {
		log.FatallnWithExitCode(2, "Fatal message exiting with exit code (note we have added a space): ", 2)
	}
	if err != nil {
		log.FatalWithExitCode(2, "Fatal message exiting with exit code:", 2)
	}
	if err != nil {
		log.FatalfWithExitCode(2, "Fatal message exiting with exit code %d", 2)
	}

	// The Fatal*IfError methods output a fatal message and exit
	// with a specified exit code if the the err parameter is not
	// nil. They are used as a short-cut for the common:
	//
	//  if err != nil {
	//      log.FatalWithExitCode(...)
	//  }
	//
	// golang programming construct.
	log.FatallnIfError(err, 3, "Fatal message if err != nil exiting with exit code: ", 3)
	log.FatalIfError(err, 3, "Fatal message if err != nil exiting with exit code:", 3)
	log.FatalfIfError(err, 3, "Fatal message if err != nil exiting with exit code %d, err = %s", 3, err)

	// The Panicln, Panic, and Panicf methods output a panic level
	// message and then call the standard builtin panic() function
	// with the message. The panic message goes to the the ErrorOutput
	// Writer, but the actual panic output will always go to
	// stderr.
	var impossibleCond bool
	if impossibleCond {
		log.Panicln("Panic message to log with panic output to stderr: ", impossibleCond)
	}
	if impossibleCond {
		log.Panic("Panic message to log with panic output to stderr:", impossibleCond)
	}
	if impossibleCond {
		log.Panicf("Panic message to log with panic output to stderr: %t", impossibleCond)
	}

	// We can exit explicitly with a specified exit code using the
	// exit() function we defined earlier. We don't need to use
	// this call to exit with exit code 0 when falling-through the
	// end of main.
	exit(5)
}
Logging to multiple logs

You can log to any number of logs with one call using the Loggers object.

package main

// This example illustrates how to use the Loggers object to send
// output to multiple logs. The Loggers object is typically used in a
// command-line program to send output to both the TTY/console and to
// a log file with one call.

import (
	"fmt"
	"io/ioutil"
	"os"

	log "github.com/apatters/go-conlog"
)

func main() {
	// Initialize the log going to the TTY/console.
	ttyLog := log.NewLogger()
	ttyLog.SetLevel(log.InfoLevel)
	formatter := log.NewStdFormatter()
	formatter.Options.LogLevelFmt = log.LogLevelFormatLongLower
	formatter.Options.ShowLogLevelColors = true
	ttyLog.SetFormatter(formatter)

	// Initialize the log going to a file.
	logFile, _ := ioutil.TempFile("", "mylogfile-")
	defer os.Remove(logFile.Name()) // You normally wouldn't delete the file.
	fileLog := log.NewLogger()
	fileLog.SetLevel(log.DebugLevel)
	fileLog.SetOutput(logFile)
	fileLog.SetErrorOutput(logFile)
	formatter = log.NewStdFormatter()
	formatter.Options.LogLevelFmt = log.LogLevelFormatShort
	formatter.Options.TimestampType = log.TimestampTypeWall
	formatter.Options.WallclockTimestampFmt = "15:04:05"
	fileLog.SetFormatter(formatter)

	// Initialize the multi-logger. We will use this one when we
	// want output to go to both logs.
	bothLogs := log.NewLoggers(ttyLog, fileLog)

	// We can send messages to individual logs or to both logs.
	ttyLog.Info("This info message only goes to the TTY.")
	fileLog.Info("This info message only goes to the log file.")
	bothLogs.Info("This info message goes to both the TTY and the log file.")

	// Individual log levels are honored.
	bothLogs.Info("This message goes to both logs because they both have log levels >= InfoLevel.")
	bothLogs.Debug("This message only goes the log file because its log level is DebugLevel.")

	// We can use the logs.SetLevel method to set the log level for all logs.
	bothLogs.SetLevel(log.DebugLevel)
	bothLogs.Debug("This debug message goes to both the TTY and the log file now that they are DebugLevel.")

	// We can enable/disable Print* methods for all logs using SetPrintEnabled.
	bothLogs.SetPrintEnabled(false)
	bothLogs.Print("This message is suppressed on both the TTY and the log file.")
	bothLogs.SetPrintEnabled(true)
	bothLogs.Println("This message goes to both TTY and the log file now that Print is re-enabled.")

	// We can use Fatal* and Panic* methods, but the messages will
	// only go the first log as the program will terminate before
	// getting to subsequent logs.
	var err error
	if err != nil {
		bothLogs.Fatal("This fatal message only goes to the TTY.")
	}
	var impossibleCond bool
	if impossibleCond {
		bothLogs.Panic("This panic message only goes to the TTY. The panic() output always goes to stderr.")
	}

	// Dump the log file to stdout so we can see the results.
	contents, _ := ioutil.ReadFile(logFile.Name())
	defer logFile.Close()
	fmt.Printf("%s\n", contents)
}

The above example program outputs:

info This info message only goes to the TTY.
info This info message goes to both the TTY and the log file.
info This message goes to both logs because they both have log levels >= InfoLevel.
debug This debug message goes to both the TTY and the log file now that they are DebugLevel.
This message goes to both TTY and the log file now that Print is re-enabled.
INFO[20:41:16] This info message only goes to the log file.
INFO[20:41:16] This info message goes to both the TTY and the log file.
INFO[20:41:16] This message goes to both logs because they both have log levels >= InfoLevel.
DEBU[20:41:16] This message only goes the log file because its log level is DebugLevel.
DEBU[20:41:16] This debug message goes to both the TTY and the log file now that they are DebugLevel.
This message goes to both TTY and the log file now that Print is re-enabled.

License

The go-conlog package is available under the MITLicense.

Thanks

Thanks to Secure64 for contributing this code.

Documentation

Overview

Package conlog provides console logging.

The conlog package is a variant of the popular https://github.com/Sirupsen/logrus package. It is optimized for console output and is meant to be used by command-line utilities with output seen interactively by the user rather than sent to a log file (although it can be used for that too).

The conlog package can be used as a drop-in replacement for the standard golang logger.

Index

Examples

Constants

View Source
const (
	// PanicLevel level. The highest level of severity, e.g.,
	// always output. Logs and then calls panic with the message.
	PanicLevel = iota

	// FatalLevel level. Logs and then calls `os.Exit(1)`. It will
	// exit even if the logging level is set to Panic.
	FatalLevel

	// ErrorLevel level. Used for errors that should definitely be
	// noted.
	ErrorLevel

	// WarnLevel level. Non-critical entries that deserve eyes.
	WarnLevel

	// InfoLevel level. General operational entries about what is
	// going on inside the application.
	InfoLevel

	// DebugLevel level. Usually only enabled when debugging. Very
	// verbose logging.
	DebugLevel
)
View Source
const (
	// Default time stamp format used when displaying wall clock
	// time. Wall clock time is the current time.Now() value when
	// the message is printed.
	DefaultWallclockTimestampFormat = time.RFC3339

	// Default time stamp format used when displaying elapsed
	// time. Elapsed time is the number of seconds since the
	// program started running is seconds.
	DefaultElapsedTimestampFormat = "%04d"
)
View Source
const (
	// LogLevelFormatUnknown is used for defensive
	// programming. You should never see this.
	LogLevelFormatUnknown = iota

	// LogLevelFormatNone disables output of the log level.
	LogLevelFormatNone

	// LogLevelFormatShort outputs the abbreviated form of the log
	// level with a trailing space, e.g., "DEBU ".
	LogLevelFormatShort

	// LogLevelFormatLongTitle outputs the full, capitalized, log
	// level with a trailing space, e.g., "Debug ".
	LogLevelFormatLongTitle

	// LogLevelFormatLongLower outputs the full, lower-case,
	// version of the log level with a trailing space, e.g.,
	// "debug ".
	LogLevelFormatLongLower
)
View Source
const (
	// TimestampTypeUnknown is used for defensive programming. You
	// should never see this.
	TimestampTypeUnknown = iota

	// TimestampTypeNone disables outputting the timestamp.
	TimestampTypeNone

	// TimestampTypeWall outputs the current wall clock time using
	// the WallclockTimestampFmt format.
	TimestampTypeWall

	// TimestampTypeElapsed outputs the elapsed time in seconds
	// since the start of execution using ElapsedTimestampFmt.
	TimestampTypeElapsed
)
View Source
const DefaultExitCode = 1

DefaultExitCode is used in the Fatal*()-style functions.

Variables

AllLevels is a constant exposing all usable logging levels.

View Source
var (
	// DiscardLogger throws away all output.
	DiscardLogger = &Logger{
		out:          ioutil.Discard,
		errOut:       ioutil.Discard,
		formatter:    NewStdFormatter(),
		level:        PanicLevel,
		printEnabled: abool.New(),
	}
)

Functions

func Debug

func Debug(args ...interface{})

Debug logs a message at level Debug to the standard logger.

func Debugf

func Debugf(format string, args ...interface{})

Debugf logs a message at level Debug to the standard logger. Arguments are handled in the manner of fmt.Printf.

func Debugln

func Debugln(args ...interface{})

Debugln logs a message at level Debug to the standard logger. It is equivalent to Debug().

func Error

func Error(args ...interface{})

Error logs a message at level Error to the standard logger.

func Errorf

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

Errorf logs a message at level Error to the standard logger. Arguments are handled in the manner of fmt.Printf.

func Errorln

func Errorln(args ...interface{})

Errorln logs a message at level Error to the standard logger. It is equivalent to Error().

func Fatal

func Fatal(args ...interface{})

Fatal logs a message at level Fatal to the standard logger and exits with the DefaultExitCode.

func FatalIfError

func FatalIfError(err error, code int, args ...interface{})

FatalIfError logs a message to the standard logger if err is not nil. It then exits with the specified code (again if the err is not nil) if code >= 0.

func FatalWithExitCode

func FatalWithExitCode(code int, args ...interface{})

FatalWithExitCode logs a message at level Fatal to the standard logger. It then exits with the specified code if code >= 0.

func Fatalf

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

Fatalf logs a message at level Fatal to the standard logger and exits with the DefaultExitCode. Arguments are handled in the manner of fmt.Printf.

func FatalfIfError

func FatalfIfError(err error, code int, format string, args ...interface{})

FatalfIfError logs a message to the standard logger if err is not nil. It then exits with the specified code (again if the err is not nil) if code >= 0.

func FatalfWithExitCode

func FatalfWithExitCode(code int, format string, args ...interface{})

FatalfWithExitCode logs a message at level Fatal to the standard logger. It then exits with the specified code if code >= 0. Arguments are handled in the manner of fmt.Printf.

func Fatalln

func Fatalln(args ...interface{})

Fatalln logs a message at level Fatal to the standard logger and exits with the DefaultExitCode. It is equivalent to Fatal().

func FatallnIfError

func FatallnIfError(err error, code int, args ...interface{})

FatallnIfError logs a message to the standard logger if err is not nil. It then exits with the specified code (again if the err is not nil) if code >= 0.

func FatallnWithExitCode

func FatallnWithExitCode(code int, args ...interface{})

FatallnWithExitCode logs a message at level Fatal to the standard logger. It then exits with the specified code if code >= 0.

func GetPrintEnabled

func GetPrintEnabled() bool

GetPrintEnabled returns the PrintEnabled setting for the standard logger.

func HandleExit

func HandleExit()

HandleExit is used to call deferred functions before exiting. It uses the panic/recover mechanism to defer exiting. This routing should be used in your main routine like so:

func main() {
   defer handleExit()
   // ready to go
}

See https://stackoverflow.com/questions/27629380/how-to-exit-a-go-program-honoring-deferred-calls for details.

Example
package main

import (
	"github.com/apatters/go-conlog"
)

// The *Fatal*WithExitCode routines use a panic/recover mechanism to
// exit with a specific exit code. This mechanism requires that we
// call the HandleExit function as the last function in main() if any
// Fatal* method is used. This is usually best done by creating a
// "deferred" call at the beginning of main() before any other
// deferred calls.

// We define an exit "wrapper" to be called in main if we want to
// explicitly exit. We do not have to call this sort of function to
// fall-through exit (with exit code 0) out of main(). You should not
// call this sort of function outside the main package.
func exit(code int) {
	panic(conlog.Exit{code})
}

func main() {
	// The exit routines use a panic/recover mechanism to exit
	// with a specific exit code. We need to call the recovery
	// routine in a defer as the first defer in main() so that it
	// gets called last.
	defer conlog.HandleExit()

	// We can exit explicitly with a specified exit code using the
	// exit() function we defined earlier. We don't need to use
	// this call to exit with exit code 0 when falling-through the
	// end of main.
	exit(5)
}
Output:

func Info

func Info(args ...interface{})

Info logs a message at level Info to the standard logger.

func Infof

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

Infof logs a message at level Info to the standard logger. Arguments are handled in the manner of fmt.Printf.

func Infoln

func Infoln(args ...interface{})

Infoln logs a message at level Info to the standard logger. It is equivalent to Info().

func Panic

func Panic(args ...interface{})

Panic logs a message at level Panic to the standard logger and then panics.

func Panicf

func Panicf(format string, args ...interface{})

Panicf logs a message at level Panic to the standard logger and then panics. Arguments are handled in the manner of fmt.Printf.

func Panicln

func Panicln(args ...interface{})

Panicln logs a message at level Panic to the standard logger. It is equivalent to Panic().

func Print

func Print(args ...interface{})

Print prints a message to the standard logger. It ignores logging levels. No logging levels, timestamps, or key files are added. No newline is added. The equivalent of fmt.Fprint.

func Printf

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

Printf prints a message to the standard logger. Ignores logging levels. No logging levels, timestamps, or key files are added. The equivalent of fmt.Fprintf.

func Println

func Println(args ...interface{})

Println a message to the standard logger. It ignores logging levels. No logging levels, timestamps, or key files are added. The equivalent of fmt.Fprintln().

func SetErrorOutput

func SetErrorOutput(w io.Writer)

SetErrorOutput sets the writer used for Error, Fatal, and Panic messages for the standard logger.

func SetFormatter

func SetFormatter(formatter Formatter)

SetFormatter sets the formatter used when printing entries to the standard logger.

func SetLevel

func SetLevel(level Level)

SetLevel sets the logger level for the standard logger.

func SetOutput

func SetOutput(w io.Writer)

SetOutput sets the writer used for Print, Debug, and Warning messages for the standard logger.

func SetPrintEnabled

func SetPrintEnabled(enabled bool)

SetPrintEnabled sets the PrintEnabled setting for the standard logger.

func Warn

func Warn(args ...interface{})

Warn logs a message at level Warn to the standard logger.

func Warnf

func Warnf(format string, args ...interface{})

Warnf logs a message at level Warn to the standard logger. Arguments are handled in the manner of fmt.Printf.

func Warning

func Warning(args ...interface{})

Warning logs a message at level Warn to the standard logger. Warning is an alias for Warn.

func Warningf

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

Warningf logs a message at level Warn to the standard logger. Arguments are handled in the manner of fmt.Printf. Warningf is an an alias for Warnf.

func Warningln

func Warningln(args ...interface{})

Warningln logs a message at level Warn to the standard logger. It is equivlent to Warning(). Warningln is an alias for Warnln.

func Warnln

func Warnln(args ...interface{})

Warnln logs a message at level Warn to the standard logger. It is equivlent to Warn().

Types

type BasicLogger added in v1.3.0

type BasicLogger interface {
	Printf(format string, args ...interface{})
	Debugf(format string, args ...interface{})
	Infof(format string, args ...interface{})
	Warnf(format string, args ...interface{})
	Warningf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
	Panicf(format string, args ...interface{})

	Print(args ...interface{})
	Debug(args ...interface{})
	Info(args ...interface{})
	Warn(args ...interface{})
	Warning(args ...interface{})
	Error(args ...interface{})
	Fatal(args ...interface{})
	Panic(args ...interface{})

	Println(args ...interface{})
	Debugln(args ...interface{})
	Infoln(args ...interface{})
	Warnln(args ...interface{})
	Warningln(args ...interface{})
	Errorln(args ...interface{})
	Fatalln(args ...interface{})
	Panicln(args ...interface{})
}

The BasicLogger interface is used for simple logging, it is suitable for using in low-level API/packages.

type ConLogger

type ConLogger interface {
	SetLevel(level Level)
	GetLevel() Level
	SetPrintEnabled(enabled bool)
	GetPrintEnabled() bool
	GetOutput() io.Writer
	SetOutput(w io.Writer)
	GetErrorOutput() io.Writer
	SetErrorOutput(w io.Writer)

	Printf(format string, args ...interface{})
	Debugf(format string, args ...interface{})
	Infof(format string, args ...interface{})
	Warnf(format string, args ...interface{})
	Warningf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
	Panicf(format string, args ...interface{})

	Print(args ...interface{})
	Debug(args ...interface{})
	Info(args ...interface{})
	Warn(args ...interface{})
	Warning(args ...interface{})
	Error(args ...interface{})
	Fatal(args ...interface{})
	Panic(args ...interface{})

	Println(args ...interface{})
	Debugln(args ...interface{})
	Infoln(args ...interface{})
	Warnln(args ...interface{})
	Warningln(args ...interface{})
	Errorln(args ...interface{})
	Fatalln(args ...interface{})
	Panicln(args ...interface{})

	FatalWithExitCode(code int, args ...interface{})
	FatalfWithExitCode(code int, format string, args ...interface{})
	FatallnWithExitCode(code int, args ...interface{})
	FatalIfError(err error, code int, args ...interface{})
	FatalfIfError(err error, code int, format string, args ...interface{})
	FatallnIfError(err error, code int, args ...interface{})
}

The ConLogger interface extends the standard interface by adding level output functions and some utiliities.

type Entry

type Entry struct {
	Log *Logger

	// Time at which the log entry was created.
	Time time.Time

	// Level the log entry was logged at: Debug, Info, Warn,
	// Error, Fatal or Panic This field will be set on entry
	// firing and the value will be equal to the one in Logger
	// struct field.
	Level Level

	// Message passed to Debug, Info, Warn, Error, Fatal or Panic.
	Message string

	// When formatter is called in entry.log(), a Buffer may be
	// set to entry.
	Buffer *bytes.Buffer
}

Entry is the final or intermediate logging entry. It's finally logged when Debug, Info, Warn, Error, Fatal or Panic is called on it.

func NewEntry

func NewEntry(log *Logger) *Entry

NewEntry is the Entry constructor.

func (*Entry) Debug

func (entry *Entry) Debug(args ...interface{})

Debug writes a message ala fmt.Print.

func (*Entry) Debugf

func (entry *Entry) Debugf(format string, args ...interface{})

Debugf writes a message ala fmt.Printf.

func (*Entry) Debugln

func (entry *Entry) Debugln(args ...interface{})

Debugln writes a message ala fmt.Println.

func (*Entry) Error

func (entry *Entry) Error(args ...interface{})

Error writes a message ala fmt.Print.

func (*Entry) Errorf

func (entry *Entry) Errorf(format string, args ...interface{})

Errorf writes a message ala fmt.Printf.

func (*Entry) Errorln

func (entry *Entry) Errorln(args ...interface{})

Errorln writes a message ala fmt.Println.

func (*Entry) Fatal

func (entry *Entry) Fatal(args ...interface{})

Fatal writes a message ala fmt.Print.

func (*Entry) Fatalf

func (entry *Entry) Fatalf(format string, args ...interface{})

Fatalf writes a message ala fmt.Printf.

func (*Entry) Fatalln

func (entry *Entry) Fatalln(args ...interface{})

Fatalln writes a message ala fmt.Println.

func (*Entry) Info

func (entry *Entry) Info(args ...interface{})

Info writes a message ala fmt.Print.

func (*Entry) Infof

func (entry *Entry) Infof(format string, args ...interface{})

Infof writes a message ala fmt.Printf.

func (*Entry) Infoln

func (entry *Entry) Infoln(args ...interface{})

Infoln writes a message ala fmt.Println.

func (*Entry) Panic

func (entry *Entry) Panic(args ...interface{})

Panic writes a message ala fmt.Print and then calls panic.

func (*Entry) Panicf

func (entry *Entry) Panicf(format string, args ...interface{})

Panicf writes a message ala fmt.Print and then calls panicf.

func (*Entry) Panicln

func (entry *Entry) Panicln(args ...interface{})

Panicln writes a message ala fmt.Println and then calls panic.

func (*Entry) Print

func (entry *Entry) Print(args ...interface{})

Print writes a message ala fmt.Print if printing is enabled, otherwise it is discarded.

func (*Entry) Printf

func (entry *Entry) Printf(format string, args ...interface{})

Printf writes a message ala fmt.Printf if printing is enabled, otherwise it is discarded. No newline is appended.

func (*Entry) Println

func (entry *Entry) Println(args ...interface{})

Println writes a message ala fmt.Println if printing is enabled, otherwise it is discarded.

func (*Entry) String

func (entry *Entry) String() (string, error)

String returns the string representation from the reader and ultimately the formatter.

func (*Entry) Warn

func (entry *Entry) Warn(args ...interface{})

Warn writes a message ala fmt.Print.

func (*Entry) Warnf

func (entry *Entry) Warnf(format string, args ...interface{})

Warnf writes a message ala fmt.Printf.

func (*Entry) Warning

func (entry *Entry) Warning(args ...interface{})

Warning writes a message ala fmt.Print. It is an alias for Warn.

func (*Entry) Warningf

func (entry *Entry) Warningf(format string, args ...interface{})

Warningf writes a message ala fmt.Printf. It is an alias for Warnf.

func (*Entry) Warningln

func (entry *Entry) Warningln(args ...interface{})

Warningln writes a message ala fmt.Println. It is an alias for Warnln.

func (*Entry) Warnln

func (entry *Entry) Warnln(args ...interface{})

Warnln writes a message ala fmt.Println.

type Exit

type Exit struct {
	Code int
}

Exit is used to wrap the exit code when making calls to Log.Fatal*() function which uses an internal panic mechanism to return the exit code.

type Formatter

type Formatter interface {
	Format(*Entry) ([]byte, error)
}

The Formatter interface is used to implement a custom Formatter. It takes an `Entry`.

Format is expected to return an array of bytes which are then logged to `log.Out`.

type FormattingOptions

type FormattingOptions struct {
	// LogLevelFmt is the format used to display the log
	// level. Defaults to LogLevelFormatNone.
	LogLevelFmt LogLevelFormat

	// ShowLogLevelColors controls showing colorized log levels if
	// output is to a TTY. Defaults to false.
	ShowLogLevelColors bool

	// TimestampTypeOutput controls the type of timestamp
	// used. The default is TimestampTypeNone.
	TimestampType TimestampType

	// WallclockTimestampFmt is the time.Format() format used when
	// displaying wall clock timestamps. Defaults to time.RFC3339.
	WallclockTimestampFmt string

	// ElapsedTimestampFmt is the format string used to display
	// elapsed time timestamps. Defaults to "%04d".
	ElapsedTimestampFmt string
}

FormattingOptions are options that control output format.

func NewFormattingOptions

func NewFormattingOptions() *FormattingOptions

NewFormattingOptions is the constructor for Formatting options.

type Level

type Level uint32

Level wraps the enumerated constants used to set and report logging levels.

func GetLevel

func GetLevel() Level

GetLevel returns the current logging level for the standard logger.

func ParseLevel

func ParseLevel(lvl string) (Level, error)

ParseLevel takes a string level and returns the log level constant.

func (Level) String

func (level Level) String() string

String converts the Level to a string. E.g. PanicLevel becomes "panic".

type LogLevelFormat

type LogLevelFormat uint32

LogLevelFormat is used to set how the log level is displayed in an output message.

type Logger

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

Logger encapsulates basic logging.

Example
// Initilize basic logging using the default constructor.
log := conlog.NewLogger()

// Messages are output/not output depending on log level. The
// log level (in ascending order are:
//
// PanicLevel
// FatalLevel
// ErrorLevel
// WarnLevel
// InfoLevel
// DebugLevel
log.SetLevel(conlog.DebugLevel)
log.SetErrorOutput(os.Stdout) // All output goes to stdout.
formatter := conlog.NewStdFormatter()
formatter.Options.LogLevelFmt = conlog.LogLevelFormatLongLower
log.SetFormatter(formatter)
// log.Panic("This is a panic message.")
// log.Fatal("This is a fatal message.")
log.Error("This is an error message.")
log.Warn("This is a warning message.")
log.Warning("This is also a warning message.")
log.Info("This is an info message.")
log.Debug("This is a debug message.")

// The default log level is Level.Info. You can set a
// different log level using SetLevel.
log.SetLevel(conlog.WarnLevel)
formatter = conlog.NewStdFormatter()
formatter.Options.LogLevelFmt = conlog.LogLevelFormatLongLower
log.SetFormatter(formatter)
log.Info("This message is above the log level so is not output.")
log.Warning("This message is at the log level so it is output.")
log.Error("This message is below the log level so it too is output.")

// There are three forms of output functions for each log
// level corresponding to the fmt.Print* functions. The
// log.Error* output functions have a log.Error(),
// Log.Errorln, and log.Errorf variations corresponding to
// fmt.Print(), fmt.Println, and fmt.Printf(). They process
// parameters in the same way as their fmt counterparts,
// except that a newline is always output.
log.SetLevel(conlog.DebugLevel)
log.Infoln("Print a number with a newline:", 4)
log.Info("Print a number also with a newline (note we have to add a space): ", 4)
log.Infof("Print a formatted number with a newline: %d", 4)

// Output is sent to stderr for log levels of PanicLevel,
// FatalLevel, and ErrorLevel. Output is sent to stdout for
// log levels above ErrorLevel. You can change this behavior
// by setting the Writers in log.out and log.errOut. For
// example, if we want all output to go to stdout, use:
log.SetErrorOutput(os.Stdout)
log.Info("This message is going to stdout.")
log.Error("This message is now also going to stdout.")

// We can send output to any Writer. For example, to send
// output for all levels to a file, we can use:
logFile, _ := ioutil.TempFile("", "mylogfile-")
defer os.Remove(logFile.Name()) // You normally wouldn't delete the file.
log.SetOutput(logFile)
log.SetErrorOutput(logFile)
log.Info("This message is going to the logfile.")
log.Error("This message is also going to the logfile.")
_ = logFile.Close()
// Dump to stdout so we can see the results.
contents, _ := ioutil.ReadFile(logFile.Name())
fmt.Printf("%s", contents)

// There are a set of Print* output methods that behave
// exactly like the corresponding fmt.Print* functions except
// that output goes to the log.out writer. Output can be
// suppressed using the SetPrintEnabled() method (enabled by
// default). Note, Print* methods are not in any way governed
// by the log level.
//
// Command-line programs should generally use these Print*
// functions in favor of the corresponding fmt versions if
// using this logging system.
//
// Unlike the log level output methods, the Print and Printf
// methods do not output a trailing newline.
log.SetOutput(os.Stdout)
log.SetErrorOutput(os.Stdout)
log.Println("Print a number with an implicit newline:", 4.0)
log.Print("Print a number with an added newline (note we have to add a space): ", 4.0, "\n")
log.Printf("Print a formatted number with an added newline: %f\n", 4.0)

// We can suppress Print* output using the SetPrintEnabled
// method. This feature can be useful for programs that have a
// --verbose option. You can disable Print* output by default
// and then enable it when the verbose flag it set.
log.SetPrintEnabled(false)
fmt.Printf("Printing enabled: %t\n", log.GetPrintEnabled())
log.Printf("This print message is suppressed.\n")
log.SetPrintEnabled(true)
fmt.Printf("Printing enabled: %t\n", log.GetPrintEnabled())
log.Printf("Print message are no longer suppressed.\n")
Output:

error This is an error message.
warning This is a warning message.
warning This is also a warning message.
info This is an info message.
debug This is a debug message.
warning This message is at the log level so it is output.
error This message is below the log level so it too is output.
info Print a number with a newline: 4
info Print a number also with a newline (note we have to add a space): 4
info Print a formatted number with a newline: 4
info This message is going to stdout.
error This message is now also going to stdout.
info This message is going to the logfile.
error This message is also going to the logfile.
Print a number with an implicit newline: 4
Print a number with an added newline (note we have to add a space): 4
Print a formatted number with an added newline: 4.000000
Printing enabled: false
Printing enabled: true
Print message are no longer suppressed.

func NewLogger

func NewLogger() *Logger

NewLogger is the constructor for Logger.

func (*Logger) Debug

func (log *Logger) Debug(args ...interface{})

Debug logs a message at level Debug on the logger.

func (*Logger) Debugf

func (log *Logger) Debugf(format string, args ...interface{})

Debugf logs a message at level Debug on the logger. Arguments are handled in the manner of fmt.Printf.

func (*Logger) Debugln

func (log *Logger) Debugln(args ...interface{})

Debugln logs a message at level Debug on the logger. It is equivalent to Debug().

func (*Logger) Error

func (log *Logger) Error(args ...interface{})

Error logs a message at level Error on the logger.

func (*Logger) Errorf

func (log *Logger) Errorf(format string, args ...interface{})

Errorf logs a message at level Error on the logger. Arguments are handled in the manner of fmt.Printf.

func (*Logger) Errorln

func (log *Logger) Errorln(args ...interface{})

Errorln logs a message at level Error on the logger. It is equivalent to Error().

func (*Logger) Fatal

func (log *Logger) Fatal(args ...interface{})

Fatal logs a message at level Fatal on the logger and exits with the DefaultExitCode.

Example
// The exit routines use a panic/recover mechanism to exit
// with a specific exit code. We need to call the recovery
// routine in a defer as the first defer in main() so that it
// gets called last.
defer conlog.HandleExit()

// Initilize basic logging using the default constructor.
log := conlog.NewLogger()

var err error

// The Fatalln, Fatal, and Fatalf methods output a message and
// exit with exit code 1. These calls append a newline to the
// message.
if err != nil {
	log.Fatalln("Fatal message exiting with exit code (note we have added a space): ", 1)
}
if err != nil {
	log.Fatal("Fatal message exiting with exit code:", 1)
}
if err != nil {
	log.Fatalf("Fatal message exiting with exit code %d", 1)
}
Output:

func (*Logger) FatalIfError

func (log *Logger) FatalIfError(err error, code int, args ...interface{})

FatalIfError logs a message to the logger if err is not nil. It then exits with the specified code (again if the err is not nil) if code >= 0.

func (*Logger) FatalWithExitCode

func (log *Logger) FatalWithExitCode(code int, args ...interface{})

FatalWithExitCode logs a message at level Fatal on the logger. It then exits with the specified code if code >= 0.

Example
// The exit routines use a panic/recover mechanism to exit
// with a specific exit code. We need to call the recovery
// routine in a defer as the first defer in main() so that it
// gets called last.
defer conlog.HandleExit()

// Initilize basic logging using the default constructor.
log := conlog.NewLogger()

var err error

// The Fatal*WithExitCode methods work like Fatalln, Fatal,
// and Fatalf except that you can specify the exit code to
// use.
if err != nil {
	log.FatallnWithExitCode(2, "Fatal message exiting with exit code (note we have added a space): ", 2)
}
if err != nil {
	log.FatalWithExitCode(2, "Fatal message exiting with exit code:", 2)
}
if err != nil {
	log.FatalfWithExitCode(2, "Fatal message exiting with exit code %d", 2)
}

// The Fatal*IfError methods output a fatal message and exit
// with a specified exit code if the the err parameter is not
// nil. They are used as a short-cut for the common:
//
//  if err != nil {
//      log.FatalWithExitCode(...)
//  }
//
// golang programming construct.
log.FatallnIfError(err, 3, "Fatal message if err != nil exiting with exit code: ", 3)
log.FatalIfError(err, 3, "Fatal message if err != nil exiting with exit code:", 3)
log.FatalfIfError(err, 3, "Fatal message if err != nil exiting with exit code %d, err = %s", 3, err)
Output:

func (*Logger) Fatalf

func (log *Logger) Fatalf(format string, args ...interface{})

Fatalf logs a message at level Fatal on the logger and exits with the DefaultExitCode. Arguments are handled in the manner of fmt.Printf.

func (*Logger) FatalfIfError

func (log *Logger) FatalfIfError(err error, code int, format string, args ...interface{})

FatalfIfError logs a message to the logger if err is not nil. It then exits with the specified code (again if the err is not nil) if code >= 0.

func (*Logger) FatalfWithExitCode

func (log *Logger) FatalfWithExitCode(code int, format string, args ...interface{})

FatalfWithExitCode logs a message at level Fatal on the logger. It then exits with the specified code if code >= 0. Arguments are handled in the manner of fmt.Printf.

func (*Logger) Fatalln

func (log *Logger) Fatalln(args ...interface{})

Fatalln logs a message at level Fatal on the logger and exits with the DefaultExitCode. It is equivalent to Fatal().

func (*Logger) FatallnIfError

func (log *Logger) FatallnIfError(err error, code int, args ...interface{})

FatallnIfError logs a message to the logger if err is not nil. It then exits with the specified code (again if the err is not nil) if code >= 0.

func (*Logger) FatallnWithExitCode

func (log *Logger) FatallnWithExitCode(code int, args ...interface{})

FatallnWithExitCode logs a message at level Fatal on the logger. It then exits with the specified exit code if code >= 0.

func (*Logger) GetErrorOutput added in v1.1.0

func (log *Logger) GetErrorOutput() io.Writer

GetErrorOutput returns the writer used for Error, Fatal, and Panic messages.

func (*Logger) GetLevel

func (log *Logger) GetLevel() Level

GetLevel returns the current logging level.

func (*Logger) GetOutput added in v1.1.0

func (log *Logger) GetOutput() io.Writer

GetOutput returns the writer used for Print, Debug, and Warning messages.

func (*Logger) GetPrintEnabled

func (log *Logger) GetPrintEnabled() bool

GetPrintEnabled returns the PrintEnabled setting.

func (*Logger) Info

func (log *Logger) Info(args ...interface{})

Info logs a message at level Info on the logger.

func (*Logger) Infof

func (log *Logger) Infof(format string, args ...interface{})

Infof logs a message at level Info on the logger. Arguments are handled in the manner of fmt.Printf.

func (*Logger) Infoln

func (log *Logger) Infoln(args ...interface{})

Infoln logs a message at level Info on logger. It is equivalent to Info().

func (*Logger) Lock

func (log *Logger) Lock()

Lock temporarily blocks output.

func (*Logger) Panic

func (log *Logger) Panic(args ...interface{})

Panic logs a message at level Panic on the logger and then panics.

Example

The Panic* methods are used to make logging the output of failed assertions consistent with the rest of the conlog logging system.

// The Panicln, Panic, and Panicf methods output a panic level
// message and then call the standard builtin panic() function
// with the message. The panic message goes to the the ErrOut
// Writer, but the underlying panic output will always go to
// stderr.

// Initilize basic logging using the default constructor.
log := conlog.NewLogger()

var impossibleCond bool
if impossibleCond {
	log.Panicln("Panic message to log with panic output to stderr: ", impossibleCond)
}
if impossibleCond {
	log.Panic("Panic message to log with panic output to stderr:", impossibleCond)
}
if impossibleCond {
	log.Panicf("Panic message to log with panic output to stderr: %t", impossibleCond)
}
Output:

func (*Logger) Panicf

func (log *Logger) Panicf(format string, args ...interface{})

Panicf logs a message at level Panic on the logger and then panics. Arguments are handled in the manner of fmt.Printf.

func (*Logger) Panicln

func (log *Logger) Panicln(args ...interface{})

Panicln logs a message at level Panic on the logger. It is equivalent to Panic().

func (*Logger) Print

func (log *Logger) Print(args ...interface{})

Print prints a message to the logger. It ignores logging levels. No logging levels, or timestamps are added. No newline is added. The equivalent of fmt.Fprint(out, ...).

Example

There are a set of Print* output methods that behave exactly like the corresponding fmt.Print* functions except that output goes to the log.Out writer. Output can be suppressed using the SetPrintEnabled() method (enabled by default). Note, Print* methods are not in any way governed by the log level.

Command-line programs should generally use these Print* methods in favor of the corresponding fmt versions if using this logging system.

Unlike the log level output methods, the Print and Printf methods do not output a trailing newline.

// Initilize basic logging using the default constructor.
log := conlog.NewLogger()

log.Print("A simple message with an added trailing newline.", "\n")
log.Print("Compress some adjacent strings", "1st", "2nd", 3, "4th", "5th", 6, 7, "\n")
log.Print("Print a number with an added trailing newline: ", 4.0, "\n")
log.Println("Print a number with an implicit newline:", 4.0)
log.Printf("Print a formatted number with an added newline: %f\n", 4.0)

// We can suppress Print* output using the SetPrintEnabled
// method. This feature can be useful for programs that have a
// --verbose option. You can disable Print* output by default
// and then enable it when the verbose flag it set.
log.SetPrintEnabled(false)
fmt.Printf("Printing enabled: %t\n", log.GetPrintEnabled())
log.Println("This print message is suppressed.")
log.SetPrintEnabled(true)
fmt.Printf("Printing enabled: %t\n", log.GetPrintEnabled())
log.Println("Print* messages are no longer suppressed.")
Output:

A simple message with an added trailing newline.
Compress some adjacent strings1st2nd34th5th6 7
Print a number with an added trailing newline: 4
Print a number with an implicit newline: 4
Print a formatted number with an added newline: 4.000000
Printing enabled: false
Printing enabled: true
Print* messages are no longer suppressed.

func (*Logger) Printf

func (log *Logger) Printf(format string, args ...interface{})

Printf prints a message to the logger. Ignores logging levels. No logging levels, or timestamps are added. The equivalent of fmt.Fprintf(out, ...).

func (*Logger) Println

func (log *Logger) Println(args ...interface{})

Println a message to the logger. It ignores logging levels. No logging levels, or timestamps, are added. The equivalent of fmt.Fprintln(out, ...).

func (*Logger) SetErrorOutput

func (log *Logger) SetErrorOutput(w io.Writer)

SetErrorOutput sets the writer used for Error, Fatal, and Panic messages.

func (*Logger) SetFormatter

func (log *Logger) SetFormatter(formatter Formatter)

SetFormatter sets the formatter used when printing entries.

func (*Logger) SetLevel

func (log *Logger) SetLevel(level Level)

SetLevel sets the logger level.

func (*Logger) SetNoLock

func (log *Logger) SetNoLock()

SetNoLock disables the use of locking. It can be used when the log files are opened with appending mode, It is then safe to write concurrently to a file (within 4k message on Linux).

func (*Logger) SetOutput

func (log *Logger) SetOutput(w io.Writer)

SetOutput sets the writer used for Print, Debug, and Warning messages.

func (*Logger) SetPrintEnabled

func (log *Logger) SetPrintEnabled(enabled bool)

SetPrintEnabled sets the PrintEnabled setting.

func (*Logger) Unlock

func (log *Logger) Unlock()

Unlock re-enables output that has been blocked with Lock().

func (*Logger) Warn

func (log *Logger) Warn(args ...interface{})

Warn logs a message at level Warn on the logger.

func (*Logger) Warnf

func (log *Logger) Warnf(format string, args ...interface{})

Warnf logs a message at level Warn on the logger. Arguments are handled in the manner of fmt.Printf.

func (*Logger) Warning

func (log *Logger) Warning(args ...interface{})

Warning logs a message at level Warn on the logger. Warning is an alias for Warn.

func (*Logger) Warningf

func (log *Logger) Warningf(format string, args ...interface{})

Warningf logs a message at level Warn on the logger. Arguments are handled in the manner of fmt.Printf. Warningf is an an alias for Warnf.

func (*Logger) Warningln

func (log *Logger) Warningln(args ...interface{})

Warningln logs a message at level Warn on the logger. It is equivlent to Warning(). Warningln is an alias for Warnln.

func (*Logger) Warnln

func (log *Logger) Warnln(args ...interface{})

Warnln logs a message at level Warn on the logger. It is equivlent to Warn().

type Loggers

type Loggers struct {
	// A list of Logger(s) to output to.
	Loggers []ConLogger
}

Loggers outputs the same message at the same log level to a list of loggers. It is often used when you want the same message to go to both the console and a log file.

Example
// Initialize the log going to the TTY/console.
ttyLog := conlog.NewLogger()
ttyLog.SetLevel(conlog.InfoLevel)
formatter := conlog.NewStdFormatter()
formatter.Options.LogLevelFmt = conlog.LogLevelFormatLongLower
formatter.Options.ShowLogLevelColors = true
ttyLog.SetFormatter(formatter)

// Initialize the log going to a file.
logFile, _ := ioutil.TempFile("", "mylogfile-")
defer os.Remove(logFile.Name()) // You normally wouldn't delete the file.
fileLog := conlog.NewLogger()
fileLog.SetLevel(conlog.DebugLevel)
fileLog.SetOutput(logFile)
fileLog.SetErrorOutput(logFile)
formatter = conlog.NewStdFormatter()
formatter.Options.LogLevelFmt = conlog.LogLevelFormatShort
formatter.Options.TimestampType = conlog.TimestampTypeWall
formatter.Options.WallclockTimestampFmt = "15:04:05"
fileLog.SetFormatter(formatter)

// Initialize the multi-logger. We will use this one when we
// want output to go to both logs.
bothLogs := conlog.NewLoggers(ttyLog, fileLog)

// We can send messages to individual logs or to both logs.
ttyLog.Info("This info message only goes to the TTY.")
fileLog.Info("This info message only goes to the log file.")
bothLogs.Info("This info message goes to both the TTY and the log file.")

// Individual log levels are honored.
bothLogs.Info("This message goes to both logs because they both have log levels >= InfoLevel.")
bothLogs.Debug("This message only goes the log file because its log level is DebugLevel.")

// We can use the logs.SetLevel method to set the log level for all logs.
bothLogs.SetLevel(conlog.DebugLevel)
bothLogs.Debug("This debug message goes to both the TTY and the log file now that they are DebugLevel.")

// We can enable/disable Print* methods for all logs using SetPrintEnabled.
bothLogs.SetPrintEnabled(false)
bothLogs.Print("This message is suppressed on both the TTY and the log file.")
bothLogs.SetPrintEnabled(true)
bothLogs.Print("This message goes to both TTY and the log file now that Print is re-enabled.")

// We can use Fatal* and Panic* methods, but the messages will
// only go the first log as the program will terminate before
// getting to subsequent logs.
var err error
if err != nil {
	bothLogs.Fatal("This fatal message only goes to the TTY.")
}
var impossibleCond bool
if impossibleCond {
	bothLogs.Panic("This panic message only goes to the TTY. The panic() output always goes to stderr.")
}
Output:

info This info message only goes to the TTY.
info This info message goes to both the TTY and the log file.
info This message goes to both logs because they both have log levels >= InfoLevel.
debug This debug message goes to both the TTY and the log file now that they are DebugLevel.
This message goes to both TTY and the log file now that Print is re-enabled.

func NewLoggers

func NewLoggers(loggers ...ConLogger) *Loggers

NewLogs is the constructor for Logs.

func (*Loggers) Debug

func (logs *Loggers) Debug(args ...interface{})

Debug logs a message at level Debug on all loggers. Arguments are handled in the manner of fmt.Print.

func (*Loggers) Debugf

func (logs *Loggers) Debugf(format string, args ...interface{})

Debugf logs a message at level Debug on all loggers. Arguments are handled in the manner of fmt.Printf.

func (*Loggers) Debugln

func (logs *Loggers) Debugln(args ...interface{})

Debugln logs a message at level Debug on all loggers. Arguments are handled in the manner of fmt.Println.

func (*Loggers) Error

func (logs *Loggers) Error(args ...interface{})

Error logs a message at level Error on all loggers. Arguments are handled in the manner of fmt.Print.

func (*Loggers) Errorf

func (logs *Loggers) Errorf(format string, args ...interface{})

Errorf logs a message at level Error on all loggers. Arguments are handled in the manner of fmt.Printf.

func (*Loggers) Errorln

func (logs *Loggers) Errorln(args ...interface{})

Errorln logs a message at level Error on all loggers. Arguments are handled in the manner of fmt.Println.

func (*Loggers) Fatal

func (logs *Loggers) Fatal(args ...interface{})

Fatal displays a message at Fatal level to the first logger and exits with DefaultExitCode error code. Arguments are handled in the manner of fmt.Print.

func (*Loggers) FatalIfError

func (logs *Loggers) FatalIfError(err error, code int, args ...interface{})

FatalIfError displays an message at Fatal level to the first logger and exits with a given exit code if err is not nil. Arguments are handled in the manner of fmt.Print.

func (*Loggers) FatalWithExitCode

func (logs *Loggers) FatalWithExitCode(code int, args ...interface{})

FatalWithExitCode displays an message at Fatal level to the first logger and exits with a given exit code. Arguments are handled in the manner of fmt.Print.

func (*Loggers) Fatalf

func (logs *Loggers) Fatalf(format string, args ...interface{})

Fatalf displays a message at Fatal level to the first logger and exits with DefaultExitCode error code. Arguments are handled in the manner of fmt.Printf.

func (*Loggers) FatalfIfError

func (logs *Loggers) FatalfIfError(err error, code int, format string, args ...interface{})

FatalfIfError displays a message at Fatal level to the first logger and exits with a given exit code and if err is not nil. Arguments are handled in the manner of fmt.Printf.

func (*Loggers) FatalfWithExitCode

func (logs *Loggers) FatalfWithExitCode(code int, format string, args ...interface{})

FatalfWithExitCode displays an message at Fatal level to the first logger and exits with a given exit code. Arguments are handled in the manner of fmt.Printf.

func (*Loggers) Fatalln

func (logs *Loggers) Fatalln(args ...interface{})

Fatalln displays a message at Fatal level to the first logger and exits with DefaultExitCode error code. Arguments are handled in the manner of fmt.Println.

func (*Loggers) FatallnIfError

func (logs *Loggers) FatallnIfError(err error, code int, args ...interface{})

FatallnIfError displays a message at Fatal level to the first logger and exits with a given exit code and if err is not nil. Arguments are handled in the manner of fmt.Printf.

func (*Loggers) FatallnWithExitCode

func (logs *Loggers) FatallnWithExitCode(code int, args ...interface{})

FatallnWithExitCode displays an message at Fatal level to the first logger and exits with a given exit code. Arguments are handled in the manner of fmt.Println.

func (*Loggers) Info

func (logs *Loggers) Info(args ...interface{})

Info logs a message at level Info on all loggers. Arguments are handled in the manner of fmt.Print.

func (*Loggers) Infof

func (logs *Loggers) Infof(format string, args ...interface{})

Infof logs a message at level Info on all loggers. Arguments are handled in the manner of fmt.Printf.

func (*Loggers) Infoln

func (logs *Loggers) Infoln(args ...interface{})

Infoln logs a message at level Info on all loggers. Arguments are handled in the manner of fmt.Println.

func (*Loggers) Panic

func (logs *Loggers) Panic(args ...interface{})

Panic displays a message to the logger at Panic level and then panics. Arguments are handled in the manner of fmt.Print.

func (*Loggers) Panicf

func (logs *Loggers) Panicf(format string, args ...interface{})

Panicf displays a message to the logger at Panic level and then panics. Arguments are handled in the manner of fmt.Printf.

func (*Loggers) Panicln

func (logs *Loggers) Panicln(args ...interface{})

Panicln displays a message to the logger at Panic level and then panics. Arguments are handled in the manner of fmt.Println.

func (*Loggers) Print

func (logs *Loggers) Print(args ...interface{})

Print print a message to the loggers. It ignores logging levels. No logging levels or timestamps are added. No newline is added. The equivalent of fmt.Fprint.

func (*Loggers) Printf

func (logs *Loggers) Printf(format string, args ...interface{})

Printf prints a message to the loggers. It ignores logging levels. No logging levels or timestamps are added. The equivalent of fmt.Fprintf.

func (*Loggers) Println

func (logs *Loggers) Println(args ...interface{})

Println prints a message to the logger. It ignores logging levels. No logging levels, timestamps, or key files are added. The equivalent of fmt.Fprintln.

func (*Loggers) SetLevel

func (logs *Loggers) SetLevel(level Level)

SetLevel sets the logger level for all loggers..

func (*Loggers) SetPrintEnabled

func (logs *Loggers) SetPrintEnabled(enabled bool)

SetPrintEnabled enables/disables Print*- output for all loggers.

func (*Loggers) Warn

func (logs *Loggers) Warn(args ...interface{})

Warn logs a message at level Warn on all loggers. Arguments are handled in the manner of fmt.Print.

func (*Loggers) Warnf

func (logs *Loggers) Warnf(format string, args ...interface{})

Warnf logs a message at level Warn on all loggers. Arguments are handled in the manner of fmt.Printf.

func (*Loggers) Warning

func (logs *Loggers) Warning(args ...interface{})

Warning logs a message at level Warning on all loggers. Arguments are handled in the manner of fmt.Print. Warning is an alias for Warn.

func (*Loggers) Warningf

func (logs *Loggers) Warningf(format string, args ...interface{})

Warningf logs a message at level Warning on all loggers. Arguments are handled in the manner of fmt.Printf. Warningf is an alias for Warnf.

func (*Loggers) Warningln

func (logs *Loggers) Warningln(args ...interface{})

Warningln logs a message at level Warning on all loggers. Arguments are handled in the manner of fmt.Println. Warningf is an alias for Warnln.

func (*Loggers) Warnln

func (logs *Loggers) Warnln(args ...interface{})

Warnln logs a message at level Warn on all loggers. Arguments are handled in the manner of fmt.Println.

type MutexWrap

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

MutexWrap is used to serialize logging output amongst goroutines.

func (*MutexWrap) Disable

func (mw *MutexWrap) Disable()

Disable disables the use of locks when logging which can result in a performance increase at the expense of the loss of serialization.

func (*MutexWrap) Lock

func (mw *MutexWrap) Lock()

Lock creates a lock on the logging mutex.

func (*MutexWrap) Unlock

func (mw *MutexWrap) Unlock()

Unlock removes the lock on the logging mutex. It should generally be called in a "defer" statement.

type StdFormatter

type StdFormatter struct {

	// Formatting options used to modify the output.
	Options *FormattingOptions

	sync.Once
	// contains filtered or unexported fields
}

StdFormatter formats logs into text.

Example
// Basic logging using the default constructor.
log := conlog.NewLogger()
log.SetErrorOutput(os.Stdout) // All output goes to stdout for this example.
log.Info("This is an info message without a leader.")
log.Warning("This is a warning message without a leader.")
log.Error("This is an error message without a leader.")

// Basic logging showing log level leaders.
formatter := conlog.NewStdFormatter()
formatter.Options.LogLevelFmt = conlog.LogLevelFormatLongTitle
log.SetFormatter(formatter)
log.Info("This is an info message with a leader.")
log.Warning("This is a warning message with a leader.")
log.Error("This is an error message with a leader.")

// The leader can be colorized if going to a tty. If output is
// going to a file or pipe, no color is used.
log.SetLevel(conlog.DebugLevel)
formatter = conlog.NewStdFormatter()
formatter.Options.LogLevelFmt = conlog.LogLevelFormatLongTitle
formatter.Options.ShowLogLevelColors = true
log.SetFormatter(formatter)
log.Debug("Debug messages are blue.")
log.Info("Info messages are green.")
log.Warn("Warning messages are yellow.")
log.Error("Error messages are red.")

// You can show the traditional logrus log levels using the
// formatter LogLevelFormatShort option:
formatter = conlog.NewStdFormatter()
formatter.Options.LogLevelFmt = conlog.LogLevelFormatShort
log.SetFormatter(formatter)
log.Debug("Debug message with a short leader.")
log.Info("Info message with a short leader.")
log.Warn("Warning message with a short leader.")
log.Error("Error message with a short leader.")

// You can show long form log levels in lower-case using the
// formatter LogLevelFormatLongLower option:
formatter = conlog.NewStdFormatter()
formatter.Options.LogLevelFmt = conlog.LogLevelFormatLongLower
log.SetFormatter(formatter)
log.Debug("Debug message with a long, lowercase leader.")
log.Info("Info message with a long, lowercase leader.")
log.Warn("Warning message with a long, lowercase leader.")
log.Error("Error message with a long, lowercase leader.")

/*
	// You can show time stamps in wall clock time with various
	// formats.
	formatter = conlog.NewStdFormatter()
	formatter.Options.TimestampType = conlog.TimestampTypeWall
	formatter.Options.LogLevelFmt = conlog.LogLevelFormatLongTitle
	log.Formatter = formatter
	log.Info("Info message with wall clock time (default RFC3339 format).")
	formatter = conlog.NewStdFormatter()
	formatter.Options.TimestampType = conlog.TimestampTypeWall
	formatter.Options.LogLevelFmt = conlog.LogLevelFormatLongTitle
	formatter.Options.WallclockTimestampFmt = time.ANSIC
	log.SetFormatter(formatter)
	log.Info("Info message with wall clock time (ANSIC format).")
	formatter = conlog.NewStdFormatter()
	formatter.Options.TimestampType = conlog.TimestampTypeWall
	formatter.Options.LogLevelFmt = conlog.LogLevelFormatLongTitle
	formatter.Options.WallclockTimestampFmt = "Jan _2 15:04:05"
	log.SetFormatter(formatter)
	log.Info("Info message with wall clock time (custom format).")

	// You can show time stamps with elapsed time and in various
	// formats.
	formatter = conlog.NewStdFormatter()
	formatter.Options.TimestampType = conlog.TimestampTypeElapsed
	formatter.Options.LogLevelFmt = conlog.LogLevelFormatLongTitle
	log.SetFormatter(formatter)
	log.Info("Info message with elapsed time (start).")
	time.Sleep(time.Second)
	log.Info("Info message with elapsed time (wait one second).")
	formatter = conlog.NewStdFormatter()
	formatter.Options.TimestampType = conlog.TimestampTypeElapsed
	formatter.Options.LogLevelFmt = conlog.LogLevelFormatLongTitle
	formatter.Options.ElapsedTimestampFmt = "%02d"
	log.SetFormatter(formatter)
	log.Info("Info message with elapsed time with custom format.")
*/psed time with custom format.")
*/
Output:

This is an info message without a leader.
This is a warning message without a leader.
This is an error message without a leader.
Info This is an info message with a leader.
Warning This is a warning message with a leader.
Error This is an error message with a leader.
Debug Debug messages are blue.
Info Info messages are green.
Warning Warning messages are yellow.
Error Error messages are red.
DEBU Debug message with a short leader.
INFO Info message with a short leader.
WARN Warning message with a short leader.
ERRO Error message with a short leader.
debug Debug message with a long, lowercase leader.
info Info message with a long, lowercase leader.
warning Warning message with a long, lowercase leader.
error Error message with a long, lowercase leader.

func NewStdFormatter

func NewStdFormatter() *StdFormatter

NewStdFormatter is the StdFormatter constructor.

func (*StdFormatter) Format

func (f *StdFormatter) Format(entry *Entry) ([]byte, error)

Format renders a single log entry.

type StdLogger

type StdLogger interface {
	Print(...interface{})
	Printf(string, ...interface{})
	Println(...interface{})

	Fatal(...interface{})
	Fatalf(string, ...interface{})
	Fatalln(...interface{})

	Panic(...interface{})
	Panicf(string, ...interface{})
	Panicln(...interface{})

	SetOutput(io.Writer)
}

The StdLogger interface is compatible with the standard library log package.

Example
package main

import (
	"os"

	log "github.com/apatters/go-conlog"
)

func main() {
	log.Print("Use Print() to print a message.\n")
	log.Println("Use Println to output a message.")
	log.Printf("Use Printf() to output a %s message.\n", "formatted")

	log.SetErrorOutput(os.Stdout) // go test only looks at stdout.
	log.Error("Use Error() to print an error message.")

}
Output:

Use Print() to print a message.
Use Println to output a message.
Use Printf() to output a formatted message.
Use Error() to print an error message.

type TimestampType

type TimestampType uint32

TimestampType is used to set what type of timestamp is displayed in output messages.

Jump to

Keyboard shortcuts

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