log

package module
v1.3.6 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2023 License: BSD-3-Clause Imports: 19 Imported by: 492

README

log

GoDoc Build Status Coverage Go Report

Other languages

简体中文 Русский

Description

log is a Go package providing enhanced logging support for Go programs. It has the following features:

  • High performance through asynchronous logging;
  • Recording message severity levels;
  • Recording message categories;
  • Recording message call stacks;
  • Filtering via severity levels and categories;
  • Customizable message format;
  • Configurable and pluggable message handling through log targets;
  • Included console, file, network, and email log targets.

Requirements

Go 1.2 or above.

Installation

Run the following command to install the package:

go get github.com/admpub/log

Getting Started

The following code snippet shows how you can use this package.

package main

import (
	"github.com/admpub/log"
)

func main() {
    // creates the root logger
	logger := log.NewLogger()

	// adds a console target and a file target
	t1 := log.NewConsoleTarget()
	t2 := log.NewFileTarget()
	t2.FileName = "app.log"
	t2.MaxLevel = log.LevelError
	logger.Targets = append(logger.Targets, t1, t2)

	logger.Open()
	defer logger.Close()

	// calls log methods to log various log messages
	logger.Error("plain text error")
	logger.Error("error with format: %v", true)
	logger.Debug("some debug info")

	// customizes log category
	l := logger.GetLogger("app.services")
	l.Info("some info")
	l.Warn("some warning")

	...
}

Loggers and Targets

A logger provides various log methods that can be called by application code to record messages of various severity levels.

A target filters log messages by their severity levels and message categories and processes the filtered messages in various ways, such as saving them in files, sending them in emails, etc.

A logger can be equipped with multiple targets each with different filtering conditions.

The following targets are included in the log package.

  • ConsoleTarget: displays filtered messages to console window
  • FileTarget: saves filtered messages in a file (supporting file rotating)
  • NetworkTarget: sends filtered messages to an address on a network
  • MailTarget: sends filtered messages in emails

You can create a logger, configure its targets, and start to use logger with the following code:

// creates the root logger
logger := log.NewLogger()
logger.Targets = append(logger.Targets, target1, target2, ...)
logger.Open()
...calling log methods...
logger.Close()

Severity Levels

You can log a message of a particular severity level (following the RFC5424 standard) by calling one of the following methods of the Logger struct:

  • Fatal(): fatal conditions.
  • Error(): error conditions.
  • Warn(): warning conditions.
  • Info(): informational purpose.
  • Debug(): debugging purpose.

Message Categories

Each log message is associated with a category which can be used to group messages. For example, you may use the same category for messages logged by the same Go package. This will allow you to selectively send messages to different targets.

When you call log.NewLogger(), a root logger is returned which logs messages using the category named as app. To log messages with a different category, call the GetLogger() method of the root logger or a parent logger to get a child logger and then call its log methods:

logger := log.NewLogger()
// the message is of category "app"
logger.Error("...")

l1 := logger.GetLogger("system")
// the message is of category "system"
l1.Error("...")

l2 := l1.GetLogger("app.models")
// the message is of category "app.models"
l2.Error("...")

Message Formatting

By default, each log message takes this format when being sent to different targets:

2015-10-22T08:39:28-04:00 [Error][app.models] something is wrong
...call stack (if enabled)...

You may customize the message format by specifying your own message formatter when calling Logger.GetLogger(). For example,

logger := log.NewLogger()
logger = logger.GetLogger("app", func (l *Logger, e *Entry) string {
    return fmt.Sprintf("%v [%v][%v] %v%v", e.Time.Format(time.RFC822Z), e.Level, e.Category, e.Message, e.CallStack)
})

Logging Call Stacks

By setting Logger.CallStackDepth as a positive number, it is possible to record call stack information for each log method call. You may further configure Logger.CallStackFilter so that only call stack frames containing the specified substring will be recorded. For example,

logger := log.NewLogger()
// record call stacks containing "myapp/src" up to 5 frames per log message
logger.CallStackDepth = 5
logger.CallStackFilter = "myapp/src"

Message Filtering

By default, messages of all severity levels will be recorded. You may customize Logger.MaxLevel to change this behavior. For example,

logger := log.NewLogger()
// only record messages between Fatal and Warning levels
logger.MaxLevel = log.LevelWarn

Besides filtering messages at the logger level, a finer grained message filtering can be done at target level. For each target, you can specify its MaxLevel similar to that with the logger; you can also specify which categories of the messages the target should handle. For example,

target := log.NewConsoleTarget()
// handle messages between Fatal and Info levels
target.MaxLevel = log.LevelInfo
// handle messages of categories which start with "system.db." or "app."
target.Categories = []string{"system.db.*", "app.*"}

Configuring Logger

When an application is deployed for production, a common need is to allow changing the logging configuration of the application without recompiling its source code. log is designed with this in mind.

For example, you can use a JSON file to specify how the application and its logger should be configured:

{
    "Logger": {
        "Targets": [
            {
                "type": "ConsoleTarget",
            },
            {
                "type": "FileTarget",
                "FileName": "app.log",
                "MaxLevel": 4   // Warning or above
            }
        ]
    }
}

Assuming the JSON file is app.json, in your application code you can use the ozzo-config package to load the JSON file and configure the logger used by the application:

package main

import (
	"github.com/go-ozzo/ozzo-config"
    "github.com/admpub/log"
)

func main() {
    c := config.New()
    c.Load("app.json")
    // register the target types to allow configuring Logger.Targets.
    c.Register("ConsoleTarget", log.NewConsoleTarget)
    c.Register("FileTarget", log.NewFileTarget)

    logger := log.NewLogger()
    if err := c.Configure(logger, "Logger"); err != nil {
        panic(err)
    }
}

To change the logger configuration, simply modify the JSON file without recompiling the Go source files.

Documentation

Overview

Package log implements logging with severity levels and message categories.

Index

Examples

Constants

View Source
const (
	// STATE INDICATORS
	Red = "🔴"
	Ylw = "🟡"
	Blu = "🔵"
	Grn = "🟢"
	Org = "🟠"
	Pnk = "🟣"

	EmojiFatal    = "💀"
	EmojiError    = "❌"
	EmojiWarn     = "🟡"
	EmojiOkay     = "✅"
	EmojiInfo     = "💬"
	EmojiProgress = "⌛️"
	EmojiDebug    = "🐛"
)

Success, Warning, Error can also be summary items. Grn, Ylw, Red are calm B/G indicator lights .

View Source
const (
	ColorFlag = iota
	ColorRow
)

Variables

View Source
var (
	DefaultStackDepth  = 5
	DefaultSkipStack   = 3
	DefaultStackFilter = `github.com/admpub/log`
)
View Source
var (
	// target console
	DefaultConsoleColorize = !color.NoColor

	// target file
	DefaultFileMaxBytes    int64 = 100 * 1024 * 1024 // 100M
	DefaultFileBackupCount       = 30                // 30

	// target network
	DefaultNetworkType    = `tcp`
	DefaultNetworkAddress = ``

	// target mail
	DefaultMailHost       = ``
	DefaultMailUsername   = ``
	DefaultMailPassword   = ``
	DefaultMailSubject    = ``
	DefaultMailSender     = ``
	DefaultMailRecipients = []string{}
)
View Source
var (
	// LevelNames maps log levels to names
	LevelNames = map[Leveler]string{
		LevelDebug:    "Debug",
		LevelProgress: "Progress",
		LevelInfo:     "Info",
		LevelOkay:     "Okay",
		LevelWarn:     "Warn",
		LevelError:    "Error",
		LevelFatal:    "Fatal",
	}

	// LevelUppers 日志大写名称前缀
	LevelUppers = map[string]string{
		`Debug`:    "DEBUG",
		"Progress": "PROGR",
		`Info`:     " INFO",
		"Okay":     " OKAY",
		`Warn`:     " WARN",
		`Error`:    "ERROR",
		`Fatal`:    "FATAL",
	}

	// Levels 所有日志等级
	Levels = map[string]Leveler{
		"Debug":    LevelDebug,
		"Progress": LevelProgress,
		"Info":     LevelInfo,
		"Okay":     LevelOkay,
		"Warn":     LevelWarn,
		"Error":    LevelError,
		"Fatal":    LevelFatal,
	}
)
View Source
var DefaultLog = &defaultLogger{Logger: New()}

DefaultLog 默认日志实例

View Source
var Emojis = map[Level]string{
	LevelFatal:    EmojiFatal,
	LevelError:    EmojiError,
	LevelWarn:     EmojiWarn,
	LevelOkay:     EmojiOkay,
	LevelInfo:     EmojiInfo,
	LevelProgress: EmojiProgress,
	LevelDebug:    EmojiDebug,
}

Functions

func Categories added in v1.2.2

func Categories() []string

func Close added in v0.1.1

func Close()

func DateFormatFilename

func DateFormatFilename(dfile string) (prefix string, suffix, dateformat string, filename string, err error)

func Debug

func Debug(a ...interface{})

func Debugf

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

func DefaultFormatter

func DefaultFormatter(l *Logger, e *Entry) string

DefaultFormatter is the default formatter used to format every log message.

func Dump added in v1.1.2

func Dump(v interface{}, returnOnly ...bool) string

func EmojiOfLevel added in v1.1.0

func EmojiOfLevel(level Level) string

func EmptyFormatter added in v1.1.5

func EmptyFormatter(l *Logger, e *Entry) string

func Error

func Error(a ...interface{})

func Errorf

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

func Fatal

func Fatal(a ...interface{})

func Fatalf

func Fatalf(format string, a ...interface{})
func ForceCreateSymlink(source, dest string) error

func GetCallSingleStack

func GetCallSingleStack(skip int, filters ...string) (fileName string, lineNo int, found bool)

GetCallSingleStack 获取单个记录

func GetCallStack

func GetCallStack(skip int, frames int, filters ...string) string

GetCallStack returns the current call stack information as a string. The skip parameter specifies how many top frames should be skipped, while the frames parameter specifies at most how many frames should be returned.

func GetLevelEmoji added in v1.1.6

func GetLevelEmoji(l Level) string

func HTTPStatusLevelName

func HTTPStatusLevelName(httpCode int) string

HTTPStatusLevelName HTTP状态码相应级别名称

func HasCategory added in v1.2.2

func HasCategory(category string) bool

func Info

func Info(a ...interface{})

func Infof

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

func IsEnabled added in v0.0.2

func IsEnabled(level Level) bool

IsEnabled 是否启用了某个等级的日志输出

func JSONFormatter

func JSONFormatter(l *Logger, e *Entry) string

JSONFormatter json格式

func NewHttpLevel

func NewHttpLevel(code int, level Leveler) *httpLevel

func NormalFormatter

func NormalFormatter(l *Logger, e *Entry) string

NormalFormatter 标准格式

func Okay added in v1.1.3

func Okay(a ...interface{})

func Okayf added in v1.1.3

func Okayf(format string, a ...interface{})

func Progress added in v1.1.3

func Progress(a ...interface{})

func Progressf added in v1.1.3

func Progressf(format string, a ...interface{})

func Warn

func Warn(a ...interface{})

func Warnf

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

func Writer

func Writer(level Level) io.Writer

Types

type Action

type Action int

Action 日志触发行为编号

const (
	// ActionNothing 无操作
	ActionNothing Action = iota
	// ActionPanic 触发Panic
	ActionPanic
	// ActionExit 退出程序
	ActionExit
)

type CallStack

type CallStack struct {
	Depth   int
	Skip    int
	Filters []string
}

CallStack 调用栈信息

type ConsoleTarget

type ConsoleTarget struct {
	*Filter
	ColorMode bool // whether to use colors to differentiate log levels
	ColorType int
	Writer    io.Writer // the writer to write log messages
	// contains filtered or unexported fields
}

ConsoleTarget writes filtered log messages to console window.

func NewConsoleTarget

func NewConsoleTarget() *ConsoleTarget

NewConsoleTarget creates a ConsoleTarget. The new ConsoleTarget takes these default options: MaxLevel: LevelDebug, ColorMode: true, Writer: os.Stdout

Example
package main

import (
	"github.com/admpub/log"
)

func main() {
	logger := log.NewLogger()

	// creates a ConsoleTarget with color mode being disabled
	target := log.NewConsoleTarget()
	target.ColorMode = false

	logger.Targets = append(logger.Targets, target)

	logger.Open()

	// ... logger is ready to use ...
}
Output:

func (*ConsoleTarget) Close

func (t *ConsoleTarget) Close()

Close closes the console target.

func (*ConsoleTarget) ColorizeFlag

func (t *ConsoleTarget) ColorizeFlag(e *Entry) string

func (*ConsoleTarget) ColorizeRow

func (t *ConsoleTarget) ColorizeRow(e *Entry) string

func (*ConsoleTarget) Open

func (t *ConsoleTarget) Open(io.Writer) error

Open prepares ConsoleTarget for processing log messages.

func (*ConsoleTarget) Process

func (t *ConsoleTarget) Process(e *Entry)

Process writes a log message using Writer.

type Entry

type Entry struct {
	Level     Leveler
	Category  string
	Message   string
	Time      time.Time
	CallStack string

	FormattedMessage string
}

Entry represents a log entry.

func (*Entry) String

func (e *Entry) String() string

String returns the string representation of the log entry

type FileTarget

type FileTarget struct {
	*Filter
	// the log file name. When Rotate is true, log file name will be suffixed
	// to differentiate different backup copies (e.g. app.log.1)
	FileName string
	// whether to enable file rotating at specific time interval or when maximum file size is reached.
	Rotate bool
	// how many log files should be kept when Rotate is true (the current log file is not included).
	// This field is ignored when Rotate is false.
	BackupCount int
	// maximum number of bytes allowed for a log file. Zero means no limit.
	// This field is ignored when Rotate is false.
	MaxBytes int64

	SymlinkName    string
	DisableSymlink bool
	// contains filtered or unexported fields
}

FileTarget writes filtered log messages to a file. FileTarget supports file rotation by keeping certain number of backup log files.

func NewFileTarget

func NewFileTarget() *FileTarget

NewFileTarget creates a FileTarget. The new FileTarget takes these default options: MaxLevel: LevelDebug, Rotate: true, BackupCount: 10, MaxBytes: 1 << 20 You must specify the FileName field.

Example
package main

import (
	"github.com/admpub/log"
)

func main() {
	logger := log.NewLogger()

	// creates a FileTarget which keeps log messages in the app.log file
	target := log.NewFileTarget()
	target.FileName = "app.log"

	logger.Targets = append(logger.Targets, target)

	logger.Open()

	// ... logger is ready to use ...
}
Output:

func (*FileTarget) ClearFiles added in v1.1.2

func (t *FileTarget) ClearFiles()

func (*FileTarget) Close

func (t *FileTarget) Close()

Close closes the file target.

func (*FileTarget) CountFiles added in v1.1.2

func (t *FileTarget) CountFiles() int

func (*FileTarget) Fd added in v1.3.5

func (t *FileTarget) Fd() (fd *os.File)

func (*FileTarget) Open

func (t *FileTarget) Open(errWriter io.Writer) (err error)

Open prepares FileTarget for processing log messages.

func (*FileTarget) Process

func (t *FileTarget) Process(e *Entry)

Process saves an allowed log message into the log file.

func (*FileTarget) Write added in v1.0.1

func (t *FileTarget) Write(b []byte) (int, error)

type Filter

type Filter struct {
	MaxLevel   Leveler          // the maximum severity level that is allowed
	Levels     map[Leveler]bool // 此属性被设置时,MaxLevel 无效
	Categories []string         // the allowed message categories. Categories can use "*" as a suffix for wildcard matching.
	// contains filtered or unexported fields
}

Filter checks if a log message meets the level and category requirements.

func (*Filter) Allow

func (t *Filter) Allow(e *Entry) bool

Allow checks if a message meets the severity level and category requirements.

func (*Filter) Init

func (t *Filter) Init()

Init initializes the filter. Init must be called before Allow is called.

func (*Filter) SetLevel

func (t *Filter) SetLevel(level interface{})

func (*Filter) SetLevels

func (t *Filter) SetLevels(levels ...Leveler)

type Formatter

type Formatter func(*Logger, *Entry) string

Formatter formats a log message into an appropriate string.

func ShortFileFormatter

func ShortFileFormatter(skipStack int, filters ...string) Formatter

ShortFileFormatter 简介文件名格式

type JSONL

type JSONL struct {
	Time      string          `bson:"time" json:"time"`
	Level     string          `bson:"level" json:"level"`
	Category  string          `bson:"category" json:"category"`
	Message   json.RawMessage `bson:"message" json:"message"`
	CallStack string          `bson:"callStack" json:"callStack"`
	Pid       int             `bson:"pid" json:"pid"`
}

JSONL json格式信息

type Level

type Level int

Level 日志等级编号

const (
	LevelFatal Level = iota
	LevelError
	LevelWarn
	LevelOkay
	LevelInfo
	LevelProgress
	LevelDebug
)

RFC5424 log message levels.

func (Level) Color

func (l Level) Color() *color.Color

Color 颜色

func (Level) Int

func (l Level) Int() int

Int 等级数值

func (Level) IsEnabled added in v0.0.2

func (l Level) IsEnabled(level Level) bool

IsEnabled 是否启用了某个等级

func (Level) Level added in v1.1.6

func (l Level) Level() Level

func (Level) String

func (l Level) String() string

String returns the string representation of the log level

func (Level) Tag

func (l Level) Tag() string

Tag 标签

type Leveler

type Leveler interface {
	fmt.Stringer
	IsEnabled(level Level) bool
	Int() int
	Tag() string
	Color() *color.Color
	Level() Level
}

Leveler 日志等级接口

func GetLevel

func GetLevel(level string) (Leveler, bool)

GetLevel 获取指定名称的等级信息

type Logger

type Logger struct {
	Category  string    // the category associated with this logger
	Formatter Formatter // message formatter
	Emoji     bool
	// contains filtered or unexported fields
}

Logger records log messages and dispatches them to various targets for further processing.

func AddTarget

func AddTarget(targets ...Target) *Logger

func Async

func Async(args ...bool) *Logger

func GetLogger

func GetLogger(category string, formatter ...Formatter) *Logger

func New

func New(args ...string) *Logger

New creates a new Logger

func NewLogger

func NewLogger(args ...string) *Logger

NewLogger creates a root logger. The new logger takes these default options: ErrorWriter: os.Stderr, BufferSize: 1024, MaxLevel: LevelDebug, Category: app, Formatter: DefaultFormatter

func SetCallStack added in v0.2.1

func SetCallStack(level Level, callStack *CallStack) *Logger

func SetEmoji added in v1.1.6

func SetEmoji(on bool) *Logger

func SetFatalAction

func SetFatalAction(action Action) *Logger

func SetFormatter

func SetFormatter(formatter Formatter) *Logger

func SetLevel

func SetLevel(level string) *Logger

func SetTarget

func SetTarget(targets ...Target) *Logger

func Sync

func Sync(args ...bool) *Logger

func UseCommonTargets

func UseCommonTargets(levelName string, targetNames ...string) *Logger

func (*Logger) AddTarget

func (l *Logger) AddTarget(targets ...Target) *Logger

AddTarget 添加日志输出Target

func (*Logger) Async

func (l *Logger) Async(args ...bool) *Logger

Async 异步日志

func (*Logger) Categories added in v1.2.2

func (l *Logger) Categories() []string

func (Logger) Close

func (l Logger) Close()

Close closes the logger and the targets. Existing messages will be processed before the targets are closed. New incoming messages will be discarded after calling this method.

func (*Logger) Debug

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

Debug logs a message for debugging purpose. Please refer to Error() for how to use this method.

func (*Logger) Debugf

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

Debugf logs a message for debugging purpose. Please refer to Error() for how to use this method.

func (*Logger) EmojiOfLevel added in v1.1.6

func (l *Logger) EmojiOfLevel(level Level) string

func (*Logger) Error

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

Error logs a message indicating an error condition. This method takes one or multiple parameters. If a single parameter is provided, it will be treated as the log message. If multiple parameters are provided, they will be passed to fmt.Sprintf() to generate the log message.

Example
package main

import (
	"github.com/admpub/log"
)

func main() {
	logger := log.NewLogger()

	logger.Targets = append(logger.Targets, log.NewConsoleTarget())

	logger.Open()

	// log without formatting
	logger.Error("a plain message")
	// log with formatting
	logger.Errorf("the value is: %v", 100)
}
Output:

func (*Logger) Errorf

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

Errorf logs a message indicating an error condition. This method takes one or multiple parameters. If a single parameter is provided, it will be treated as the log message. If multiple parameters are provided, they will be passed to fmt.Sprintf() to generate the log message.

func (*Logger) Fatal

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

Fatal fatal

func (*Logger) Fatalf

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

Fatalf fatal

func (*Logger) GetLogger

func (l *Logger) GetLogger(category string, formatter ...Formatter) *Logger

GetLogger creates a logger with the specified category and log formatter. Messages logged through this logger will carry the same category name. The formatter, if not specified, will inherit from the calling logger. It will be used to format all messages logged through this logger.

func (*Logger) HasCategory added in v1.2.2

func (l *Logger) HasCategory(category string) bool

func (*Logger) Info

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

Info logs a message for informational purpose. Please refer to Error() for how to use this method.

func (*Logger) Infof

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

Infof logs a message for informational purpose. Please refer to Error() for how to use this method.

func (*Logger) IsEnabled added in v0.0.2

func (l *Logger) IsEnabled(level Level) bool

IsEnabled 是否启用了某个等级的日志输出

func (*Logger) Log

func (l *Logger) Log(level Leveler, a ...interface{})

Log logs a message of a specified severity level.

func (*Logger) Logf

func (l *Logger) Logf(level Leveler, format string, a ...interface{})

Logf logs a message of a specified severity level.

func (*Logger) Okay added in v1.1.0

func (l *Logger) Okay(a ...interface{})

Okay logs a message indicating an okay condition.

func (*Logger) Okayf added in v1.1.0

func (l *Logger) Okayf(format string, a ...interface{})

Okayf logs a message indicating an okay condition.

func (Logger) Open

func (l Logger) Open() error

Open prepares the logger and the targets for logging purpose. Open must be called before any message can be logged.

func (Logger) Pid added in v0.3.0

func (l Logger) Pid() int

func (*Logger) Progress added in v1.1.0

func (l *Logger) Progress(a ...interface{})

Progress logs a message for how things are progressing.

func (*Logger) Progressf added in v1.1.0

func (l *Logger) Progressf(format string, a ...interface{})

Progressf logs a message for how things are progressing.

func (*Logger) SetCallStack added in v0.2.1

func (l *Logger) SetCallStack(level Level, callStack *CallStack) *Logger

SetCallStack 设置各个等级的call stack配置

func (*Logger) SetEmoji added in v1.1.6

func (l *Logger) SetEmoji(on bool) *Logger

func (*Logger) SetFatalAction

func (l *Logger) SetFatalAction(action Action) *Logger

SetFatalAction 设置Fatal类型日志的行为

func (*Logger) SetFormatter

func (l *Logger) SetFormatter(formatter Formatter) *Logger

SetFormatter 设置日志格式化处理函数

func (*Logger) SetLevel

func (l *Logger) SetLevel(level string) *Logger

SetLevel 添加日志输出等级

func (*Logger) SetTarget

func (l *Logger) SetTarget(targets ...Target) *Logger

SetTarget 设置日志输出Target

func (*Logger) Sync

func (l *Logger) Sync(args ...bool) *Logger

Sync 同步日志

func (*Logger) Warn

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

Warn logs a message indicating a warning condition. Please refer to Error() for how to use this method.

func (*Logger) Warnf

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

Warnf logs a message indicating a warning condition. Please refer to Error() for how to use this method.

func (*Logger) Writer

func (l *Logger) Writer(level Level) io.Writer

Writer 日志输出Writer

type LoggerWriter

type LoggerWriter struct {
	Level Leveler
	*Logger
}

func (LoggerWriter) Close

func (l LoggerWriter) Close()

Close closes the logger and the targets. Existing messages will be processed before the targets are closed. New incoming messages will be discarded after calling this method.

func (LoggerWriter) Open

func (l LoggerWriter) Open() error

Open prepares the logger and the targets for logging purpose. Open must be called before any message can be logged.

func (LoggerWriter) Pid added in v0.3.0

func (l LoggerWriter) Pid() int

func (*LoggerWriter) Printf

func (l *LoggerWriter) Printf(format string, v ...interface{})

func (*LoggerWriter) Println

func (l *LoggerWriter) Println(v ...interface{})

func (*LoggerWriter) Write

func (l *LoggerWriter) Write(p []byte) (n int, err error)

type MailTarget

type MailTarget struct {
	*Filter
	Host       string   // SMTP server address
	Username   string   // SMTP server login username
	Password   string   // SMTP server login password
	Subject    string   // the mail subject
	Sender     string   // the mail sender
	Recipients []string // the mail recipients
	BufferSize int      // the size of the message channel.
	// contains filtered or unexported fields
}

MailTarget sends log messages in emails via an SMTP server.

func NewMailTarget

func NewMailTarget() *MailTarget

NewMailTarget creates a MailTarget. The new MailTarget takes these default options: MaxLevel: LevelDebug, BufferSize: 1024. You must specify these fields: Host, Username, Subject, Sender, and Recipients.

Example
package main

import (
	"github.com/admpub/log"
)

func main() {
	logger := log.NewLogger()

	// creates a MailTarget which sends emails to admin@example.com
	target := log.NewMailTarget()
	target.Host = "smtp.example.com"
	target.Username = "foo"
	target.Password = "bar"
	target.Subject = "log messages for foobar"
	target.Sender = "admin@example.com"
	target.Recipients = []string{"admin@example.com"}

	logger.Targets = append(logger.Targets, target)

	logger.Open()

	// ... logger is ready to use ...
}
Output:

func (*MailTarget) Close

func (t *MailTarget) Close()

Close closes the mail target.

func (*MailTarget) Open

func (t *MailTarget) Open(errWriter io.Writer) error

Open prepares MailTarget for processing log messages.

func (*MailTarget) Process

func (t *MailTarget) Process(e *Entry)

Process puts filtered log messages into a channel for sending in emails.

type NetworkTarget

type NetworkTarget struct {
	*Filter
	// the network to connect to. Valid networks include
	// tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only),
	// "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4"
	// (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and
	// "unixpacket".
	Network string
	// the address on the network to connect to.
	// For TCP and UDP networks, addresses have the form host:port.
	// If host is a literal IPv6 address it must be enclosed
	// in square brackets as in "[::1]:80" or "[ipv6-host%zone]:80".
	Address string
	// whether to use a persistent network connection.
	// If this is false, for every message to be sent, a network
	// connection will be open and closed.
	Persistent bool
	// the size of the message channel.
	BufferSize int
	// contains filtered or unexported fields
}

NetworkTarget sends log messages over a network connection.

func NewNetworkTarget

func NewNetworkTarget() *NetworkTarget

NewNetworkTarget creates a NetworkTarget. The new NetworkTarget takes these default options: MaxLevel: LevelDebug, Persistent: true, BufferSize: 1024. You must specify the Network and Address fields.

Example
package main

import (
	"github.com/admpub/log"
)

func main() {
	logger := log.NewLogger()

	// creates a NetworkTarget which uses tcp network and address :10234
	target := log.NewNetworkTarget()
	target.Network = "tcp"
	target.Address = ":10234"

	logger.Targets = append(logger.Targets, target)

	logger.Open()

	// ... logger is ready to use ...
}
Output:

func (*NetworkTarget) Close

func (t *NetworkTarget) Close()

Close closes the network target.

func (*NetworkTarget) Open

func (t *NetworkTarget) Open(errWriter io.Writer) error

Open prepares NetworkTarget for processing log messages.

func (*NetworkTarget) Process

func (t *NetworkTarget) Process(e *Entry)

Process puts filtered log messages into a channel for sending over network.

type SyslogTarget added in v1.1.0

type SyslogTarget struct {
	*Filter
	Writer *syslog.Writer
	// contains filtered or unexported fields
}

func NewSyslogTarget added in v1.1.0

func NewSyslogTarget(prefix string) (*SyslogTarget, error)

func (*SyslogTarget) Close added in v1.1.0

func (t *SyslogTarget) Close()

func (*SyslogTarget) Open added in v1.1.0

func (t *SyslogTarget) Open(io.Writer) error

func (*SyslogTarget) Process added in v1.1.0

func (t *SyslogTarget) Process(e *Entry)

type Target

type Target interface {
	// Open prepares the target for processing log messages.
	// Open will be invoked when Logger.Open() is called.
	// If an error is returned, the target will be removed from the logger.
	// errWriter should be used to write errors found while processing log messages.
	Open(errWriter io.Writer) error
	// Process processes an incoming log message.
	Process(*Entry)
	// Close closes a target.
	// Close is called when Logger.Close() is called, which gives each target
	// a chance to flush the logged messages to their destination storage.
	Close()
	SetLevel(interface{})
	SetLevels(...Leveler)
}

Target represents a target where the logger can send log messages to for further processing.

type WriteCloserTarget

type WriteCloserTarget struct {
	io.WriteCloser
	*Filter
	// contains filtered or unexported fields
}

WriteCloserTarget writes filtered log messages to a io.WriteCloser.

func NewWriteCloserTarget

func NewWriteCloserTarget(w io.WriteCloser) *WriteCloserTarget

NewWriteCloserTarget creates a WriteCloserTarget.

func (*WriteCloserTarget) Close

func (t *WriteCloserTarget) Close()

Close closes the file target.

func (*WriteCloserTarget) Open

func (t *WriteCloserTarget) Open(errWriter io.Writer) (err error)

Open nothing.

func (*WriteCloserTarget) Process

func (t *WriteCloserTarget) Process(e *Entry)

Process writes a log message using Writer.

Jump to

Keyboard shortcuts

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