Documentation ¶
Overview ¶
package log4j provides level-based and highly configurable logging.
Enhanced Logging ¶
This is inspired by the logging functionality in Java. Essentially, you create a Logger object and create output filters for it. You can send whatever you want to the Logger, and it will filter that based on your settings and send it to the outputs. This way, you can put as much debug code in your program as you want, and when you're done you can filter out the mundane messages so only the important ones show up.
Utility functions are provided to make life easier. Here is some example code to get started:
log := log4go.NewLogger() log.AddFilter("stdout", log4go.DEBUG, log4go.NewConsoleLogWriter()) log.AddFilter("log", log4go.FINE, log4go.NewFileLogWriter("example.log", true)) log.Info("The time is now: %s", time.LocalTime().Format("15:04:05 MST 2006/01/02"))
The first two lines can be combined with the utility NewDefaultLogger:
log := log4go.NewDefaultLogger(log4go.DEBUG) log.AddFilter("log", log4go.FINE, log4go.NewFileLogWriter("example.log", true)) log.Info("The time is now: %s", time.LocalTime().Format("15:04:05 MST 2006/01/02"))
Usage notes:
- The ConsoleLogWriter does not display the source of the message to standard output, but the FileLogWriter does.
- The utility functions (Info, Debug, Warn, etc) derive their source from the calling function, and this incurs extra overhead.
Changes from 2.0:
- The external interface has remained mostly stable, but a lot of the internals have been changed, so if you depended on any of this or created your own LogWriter, then you will probably have to update your code. In particular, Logger is now a map and ConsoleLogWriter is now a channel behind-the-scenes, and the LogWrite method no longer has return values.
Future work: (please let me know if you think I should work on any of these particularly)
- Log file rotation
- Logging configuration files ala log4j
- Have the ability to remove filters?
- Have GetInfoChannel, GetDebugChannel, etc return a chan string that allows for another method of logging
- Add an XML filter type
Index ¶
- Constants
- Variables
- func BytesToString(b []byte) string
- func Close()
- func Debug(arg0 interface{}, args ...interface{})
- func Error(arg0 interface{}, args ...interface{}) error
- func ErrorLog(arg0 interface{}, args ...interface{})
- func Exit(args ...interface{})
- func Exitf(format string, args ...interface{})
- func Fatal(arg0 interface{}, args ...interface{}) error
- func FatalLog(arg0 interface{}, args ...interface{})
- func FormatLogRecord(format string, rec *LogRecord) string
- func Info(arg0 interface{}, args ...interface{})
- func Log(lvl Level, source, message string)
- func Logc(lvl Level, closure func() string)
- func Logf(lvl Level, format string, args ...interface{})
- func ReadFile(path string) (string, error)
- func SetConn(config SocketConfig)
- func SetConsole(config ConsoleConfig)
- func SetDefaultLog(filter *Filter)
- func SetFile(config FileConfig)
- func Stderr(args ...interface{})
- func Stderrf(format string, args ...interface{})
- func Stdout(args ...interface{})
- func Stdoutf(format string, args ...interface{})
- func StringToBytes(s string) []byte
- func Trace(arg0 interface{}, args ...interface{})
- func Warn(arg0 interface{}, args ...interface{}) error
- func WarnLog(arg0 interface{}, args ...interface{})
- type ConnWriter
- type ConsoleConfig
- type ConsoleLogWriter
- type FileConfig
- type FileLogWriter
- func (w *FileLogWriter) Close()
- func (w *FileLogWriter) LogWrite(rec *LogRecord)
- func (w *FileLogWriter) Rotate()
- func (w *FileLogWriter) SetFormat(format string)
- func (w *FileLogWriter) SetHeadFoot(head, foot string) *FileLogWriter
- func (w *FileLogWriter) SetRotate(rotate bool) *FileLogWriter
- func (w *FileLogWriter) SetRotateDaily(daily bool) *FileLogWriter
- func (w *FileLogWriter) SetRotateLines(MaxLines int) *FileLogWriter
- func (w *FileLogWriter) SetRotateSize(maxsize int) *FileLogWriter
- func (w *FileLogWriter) SetRotatemaxBackup(maxBackup int) *FileLogWriter
- func (w *FileLogWriter) SetSanitize(sanitize bool) *FileLogWriter
- func (w *FileLogWriter) Write(p []byte) (n int, err error)
- type Filter
- func (f *Filter) Debug(arg0 interface{}, args ...interface{})
- func (f *Filter) Error(arg0 interface{}, args ...interface{})
- func (f *Filter) Fatal(arg0 interface{}, args ...interface{})
- func (f *Filter) Info(arg0 interface{}, args ...interface{})
- func (f *Filter) Log(lvl Level, source, message string)
- func (f *Filter) Logc(lvl Level, closure func() string)
- func (f *Filter) Logf(lvl Level, format string, args ...interface{})
- func (f *Filter) Trace(arg0 interface{}, args ...interface{})
- func (f *Filter) Warn(arg0 interface{}, args ...interface{})
- type FormatLogWriter
- type Level
- type LogConfig
- type LogRecord
- type LogWriter
- type Logger
- func (log Logger) AddFilter(name string, lvl Level, writer LogWriter, categorys ...string) Logger
- func (log Logger) Close()
- func (log Logger) Debug(arg0 interface{}, args ...interface{})
- func (log Logger) Error(arg0 interface{}, args ...interface{}) error
- func (log Logger) FATAL(arg0 interface{}, args ...interface{}) error
- func (log Logger) GetDefaultFilter() *Filter
- func (log Logger) Info(arg0 interface{}, args ...interface{})
- func (log Logger) Log(lvl Level, source, message string)
- func (log Logger) Logc(lvl Level, closure func() string)
- func (log Logger) Logf(lvl Level, format string, args ...interface{})
- func (log Logger) Trace(arg0 interface{}, args ...interface{})
- func (log Logger) Warn(arg0 interface{}, args ...interface{}) error
- type SocketConfig
Constants ¶
const FORMAT = "[%A][%L][%P] %F:%M"
Variables ¶
var ( // LogBufferLength specifies how many log messages a particular log4go // logger can buffer at a time before writing them. LogBufferLength = 32 )
***** Variables *****
var Project = "App-Api"
Functions ¶
func BytesToString ¶ added in v1.0.1
BytesToString converts byte slice to string.
func Debug ¶
func Debug(arg0 interface{}, args ...interface{})
Utility for debug log messages When given a string as the first argument, this behaves like Logf but with the DEBUG log level (e.g. the first argument is interpreted as a format for the latter arguments) When given a closure of type func()string, this logs the string returned by the closure iff it will be logged. The closure runs at most one time. When given anything else, the log message will be each of the arguments formatted with %v and separated by spaces (ala Sprint). Wrapper for (*Logger).Debug
func Error ¶
func Error(arg0 interface{}, args ...interface{}) error
Utility for error log messages (returns an error for easy function returns) (see Debug() for parameter explanation) These functions will execute a closure exactly once, to build the error message for the return Wrapper for (*Logger).Error
func ErrorLog ¶ added in v1.0.3
func ErrorLog(arg0 interface{}, args ...interface{})
no err return Error
func Fatal ¶
func Fatal(arg0 interface{}, args ...interface{}) error
Utility for critical log messages (returns an error for easy function returns) (see Debug() for parameter explanation) These functions will execute a closure exactly once, to build the error message for the return Wrapper for (*Logger).Critical
func FatalLog ¶ added in v1.0.3
func FatalLog(arg0 interface{}, args ...interface{})
no err return Fatal
func FormatLogRecord ¶
Known format codes: %A - Time (2006-01-02T15:04:05.000Z) means all %T - Time (15:04:05 MST) %t - Time (15:04) %D - Date (2006/01/02) %d - Date (01/02/06) %L - Level (FNST, FINE, DEBG, TRAC, WARN, EROR, CRIT) %S - Source %M - Message Ignores unknown formats Recommended: "[%D %T] [%L] (%S) %M"
func Info ¶
func Info(arg0 interface{}, args ...interface{})
Utility for info log messages (see Debug() for parameter explanation) Wrapper for (*Logger).Info
func SetConn ¶
func SetConn(config SocketConfig)
func SetConsole ¶
func SetConsole(config ConsoleConfig)
Formats: map[string]string{ // TODO(kevlar): How can I do this so it'll work outside of PST? FORMAT_DEFAULT: "[2009/02/13 23:31:30 UTC] [EROR] (source) message\n", FORMAT_SHORT: "[23:31 13/02/09] [EROR] message\n", FORMAT_ABBREV: "[EROR] message\n", },
func SetDefaultLog ¶
func SetDefaultLog(filter *Filter)
func SetFile ¶ added in v1.0.2
func SetFile(config FileConfig)
func StringToBytes ¶ added in v1.0.1
StringToBytes converts string to byte slice.
func Trace ¶
func Trace(arg0 interface{}, args ...interface{})
Utility for trace log messages (see Debug() for parameter explanation) Wrapper for (*Logger).Trace
func Warn ¶
func Warn(arg0 interface{}, args ...interface{}) error
Utility for warn log messages (returns an error for easy function returns) (see Debug() for parameter explanation) These functions will execute a closure exactly once, to build the error message for the return Wrapper for (*Logger).Warn
Types ¶
type ConnWriter ¶
type ConnWriter struct { sync.Mutex ReconnectOnMsg bool `json:"reconnectOnMsg"` Reconnect bool `json:"reconnect"` Net string `json:"net"` Addr string `json:"addr"` Level Level `json:"level"` // contains filtered or unexported fields }
ConnWriter implements LoggerInterface. it writes messages in keep-live tcp connection.
func NewConn ¶
func NewConn(Net, Addr, format string, level Level) *ConnWriter
NewConn create new ConnWrite returning as LoggerInterface.
func (*ConnWriter) Close ¶
func (c *ConnWriter) Close()
func (*ConnWriter) LogWrite ¶
func (c *ConnWriter) LogWrite(rec *LogRecord)
func (*ConnWriter) SetFormat ¶
func (c *ConnWriter) SetFormat(format string)
type ConsoleConfig ¶
type ConsoleLogWriter ¶
type ConsoleLogWriter struct {
// contains filtered or unexported fields
}
This is the standard writer that prints to standard output.
func NewConsoleLogWriter ¶
func NewConsoleLogWriter() *ConsoleLogWriter
This creates a new ConsoleLogWriter
func (*ConsoleLogWriter) Close ¶
func (c *ConsoleLogWriter) Close()
Close stops the logger from sending messages to standard output. Attempts to send log messages to this logger after a Close have undefined behavior.
func (*ConsoleLogWriter) LogWrite ¶
func (c *ConsoleLogWriter) LogWrite(rec *LogRecord)
This is the ConsoleLogWriter's output method. This will block if the output buffer is full.
func (*ConsoleLogWriter) SetFormat ¶
func (c *ConsoleLogWriter) SetFormat(format string)
type FileConfig ¶
type FileConfig struct { Enable bool `json:"enable"` Category string `json:"category"` Level string `json:"level"` Filename string `json:"filename"` // %T - Time (15:04:05 MST) // %t - Time (15:04) // %D - Date (2006/01/02) // %d - Date (01/02/06) // %L - Level (FNST, FINE, DEBG, TRAC, WARN, EROR, CRIT) // %S - Source // %M - Message // %C - Category // It ignores unknown format strings (and removes them) // Recommended: "[%D %T] [%C] [%L] (%S) %M"// Pattern string `json:"pattern"` Rotate bool `json:"rotate"` Maxsize string `json:"maxsize"` // \d+[KMG]? Suffixes are in terms of 2**10 MaxLines string `json:"MaxLines"` //\d+[KMG]? Suffixes are in terms of thousands Daily bool `json:"daily"` //Automatically rotates by day Sanitize bool `json:"sanitize"` //Sanitize newlines to prevent log injection }
type FileLogWriter ¶
type FileLogWriter struct { // Rotate at linecount MaxLines int MaxLinesCurLines int // contains filtered or unexported fields }
This log writer sends output to a file
func NewFileLogWriter ¶
func NewFileLogWriter(fileName string, rotate bool, daily bool) *FileLogWriter
NewFileLogWriter creates a new LogWriter which writes to the given file and has rotation enabled if rotate is true.
If rotate is true, any time a new log file is opened, the old one is renamed with a .### extension to preserve it. The various Set* methods can be used to configure log rotation based on lines, size, and daily.
The standard log-line format is:
[%D %T] [%L] (%S) %M
func (*FileLogWriter) Close ¶
func (w *FileLogWriter) Close()
func (*FileLogWriter) LogWrite ¶
func (w *FileLogWriter) LogWrite(rec *LogRecord)
This is the FileLogWriter's output method
func (*FileLogWriter) SetFormat ¶
func (w *FileLogWriter) SetFormat(format string)
Set the logging format (chainable). Must be called before the first log message is written.
func (*FileLogWriter) SetHeadFoot ¶
func (w *FileLogWriter) SetHeadFoot(head, foot string) *FileLogWriter
Set the logfile header and footer (chainable). Must be called before the first log message is written. These are formatted similar to the FormatLogRecord (e.g. you can use %D and %T in your header/footer for date and time).
func (*FileLogWriter) SetRotate ¶
func (w *FileLogWriter) SetRotate(rotate bool) *FileLogWriter
SetRotate changes whether or not the old logs are kept. (chainable) Must be called before the first log message is written. If rotate is false, the files are overwritten; otherwise, they are rotated to another file before the new log is opened.
func (*FileLogWriter) SetRotateDaily ¶
func (w *FileLogWriter) SetRotateDaily(daily bool) *FileLogWriter
Set rotate daily (chainable). Must be called before the first log message is written.
func (*FileLogWriter) SetRotateLines ¶
func (w *FileLogWriter) SetRotateLines(MaxLines int) *FileLogWriter
Set rotate at linecount (chainable). Must be called before the first log message is written.
func (*FileLogWriter) SetRotateSize ¶
func (w *FileLogWriter) SetRotateSize(maxsize int) *FileLogWriter
Set rotate at size (chainable). Must be called before the first log message is written.
func (*FileLogWriter) SetRotatemaxBackup ¶
func (w *FileLogWriter) SetRotatemaxBackup(maxBackup int) *FileLogWriter
Set max backup files. Must be called before the first log message is written.
func (*FileLogWriter) SetSanitize ¶
func (w *FileLogWriter) SetSanitize(sanitize bool) *FileLogWriter
SetSanitize changes whether or not the sanitization of newline characters takes place. This is to prevent log injection, although at some point the sanitization of other non-printable characters might be valueable just to prevent binary data from mucking up the logs.
type Filter ¶
A Filter represents the log level below which no log records are written to the associated LogWriter.
func (*Filter) Debug ¶
func (f *Filter) Debug(arg0 interface{}, args ...interface{})
Debug is a utility method for debug f messages. The behavior of Debug depends on the first argument:
- arg0 is a string When given a string as the first argument, this behaves like ff but with the DEBUG f level: the first argument is interpreted as a format for the latter arguments.
- arg0 is a func()string When given a closure of type func()string, this fs the string returned by the closure iff it will be fged. The closure runs at most one time.
- arg0 is interface{} When given anything else, the f message will be each of the arguments formatted with %v and separated by spaces (ala Sprint).
func (*Filter) Error ¶
func (f *Filter) Error(arg0 interface{}, args ...interface{})
Error fs a message at the error f level and returns the formatted error, See Warn for an explanation of the performance and Debug for an explanation of the parameters.
func (*Filter) Fatal ¶
func (f *Filter) Fatal(arg0 interface{}, args ...interface{})
Fatal fs a message at the error f level and returns the formatted error, See Fatal for an explanation of the performance and Debug for an explanation of the parameters.
func (*Filter) Info ¶
func (f *Filter) Info(arg0 interface{}, args ...interface{})
Info fs a message at the info f level. See Debug for an explanation of the arguments.
func (*Filter) Logc ¶
Logc logs a string returned by the closure at the given log level, using the caller as its source. If no log message would be written, the closure is never called.
func (*Filter) Logf ¶
Logf logs a formatted log message at the given log level, using the caller as its source.
func (*Filter) Trace ¶
func (f *Filter) Trace(arg0 interface{}, args ...interface{})
Trace fs a message at the trace f level. See Debug for an explanation of the arguments.
func (*Filter) Warn ¶
func (f *Filter) Warn(arg0 interface{}, args ...interface{})
Warn fs a message at the warning f level and returns the formatted error. At the warning level and higher, there is no performance benefit if the message is not actually fged, because all formats are processed and all closures are executed to format the error message. See Debug for further explanation of the arguments.
type FormatLogWriter ¶
type FormatLogWriter chan *LogRecord
This is the standard writer that prints to standard output.
func NewFormatLogWriter ¶
func NewFormatLogWriter(out io.Writer, format string) FormatLogWriter
This creates a new FormatLogWriter
func (FormatLogWriter) Close ¶
func (w FormatLogWriter) Close()
Close stops the logger from sending messages to standard output. Attempts to send log messages to this logger after a Close have undefined behavior.
func (FormatLogWriter) LogWrite ¶
func (w FormatLogWriter) LogWrite(rec *LogRecord)
This is the FormatLogWriter's output method. This will block if the output buffer is full.
type LogConfig ¶
type LogConfig struct { Console *ConsoleConfig `json:"console"` Files []*FileConfig `json:"files"` Sockets []*SocketConfig `json:"sockets"` }
LogConfig presents json log config struct
type LogRecord ¶
type LogRecord struct { Level Level // The log level Created time.Time // The time at which the log message was created (nanoseconds) Source string // The message source Message string // The log message Category string // The log group }
A LogRecord contains all of the pertinent information for each message
type LogWriter ¶
type LogWriter interface { // This will be called to log a LogRecord message. LogWrite(rec *LogRecord) // This should clean up anything lingering about the LogWriter, as it is called before // the LogWriter is removed. LogWrite should not be called after Close. Close() SetFormat(format string) Write(p []byte) (n int, err error) }
This is an interface for anything that should be able to write logs
type Logger ¶
A Logger represents a collection of Filters through which log messages are written.
var (
Global Logger
)
func NewConsoleLogger ¶
Create a new logger with a "stdout" filter configured to send log messages at or above lvl to standard output.
DEPRECATED: use NewDefaultLogger instead.
func NewDefaultLogger ¶
Create a new logger with a "stdout" filter configured to send log messages at or above lvl to standard output.
func (Logger) AddFilter ¶
Add a new LogWriter to the Logger which will only log messages at lvl or higher. This function should not be called from multiple goroutines. Returns the logger for chaining.
func (Logger) Close ¶
func (log Logger) Close()
Closes all log writers in preparation for exiting the program or a reconfiguration of logging. Calling this is not really imperative, unless you want to guarantee that all log messages are written. Close removes all filters (and thus all LogWriters) from the logger.
func (Logger) Debug ¶
func (log Logger) Debug(arg0 interface{}, args ...interface{})
Debug is a utility method for debug log messages. The behavior of Debug depends on the first argument:
- arg0 is a string When given a string as the first argument, this behaves like Logf but with the DEBUG log level: the first argument is interpreted as a format for the latter arguments.
- arg0 is a func()string When given a closure of type func()string, this logs the string returned by the closure iff it will be logged. The closure runs at most one time.
- arg0 is interface{} When given anything else, the log message will be each of the arguments formatted with %v and separated by spaces (ala Sprint).
func (Logger) Error ¶
Error logs a message at the error log level and returns the formatted error, See Warn for an explanation of the performance and Debug for an explanation of the parameters.
func (Logger) FATAL ¶
Critical logs a message at the critical log level and returns the formatted error, See Warn for an explanation of the performance and Debug for an explanation of the parameters.
func (Logger) GetDefaultFilter ¶
func (Logger) Info ¶
func (log Logger) Info(arg0 interface{}, args ...interface{})
Info logs a message at the info log level. See Debug for an explanation of the arguments.
func (Logger) Logc ¶
Logc logs a string returned by the closure at the given log level, using the caller as its source. If no log message would be written, the closure is never called.
func (Logger) Logf ¶
Logf logs a formatted log message at the given log level, using the caller as its source.
func (Logger) Trace ¶
func (log Logger) Trace(arg0 interface{}, args ...interface{})
Trace logs a message at the trace log level. See Debug for an explanation of the arguments.
func (Logger) Warn ¶
Warn logs a message at the warning log level and returns the formatted error. At the warning level and higher, there is no performance benefit if the message is not actually logged, because all formats are processed and all closures are executed to format the error message. See Debug for further explanation of the arguments.