tlog

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2024 License: Apache-2.0, BSD-2-Clause, BSD-3-Clause, + 2 more Imports: 14 Imported by: 1

README

tlog: The log module extracted from trpc-group/trpc-go

GitHub license GitHub stars

tlog is a lightweight and flexible logging library for Go applications, extracted from the trpc-group/trpc-go project. It provides a simple way to configure and manage logs in your applications with various output configurations and levels.

Features

  • Multiple Output Configurations: Support for different writers like console and file.
  • Log Level Management: Easily set log levels for different parts of your application.
  • Custom Formatters: JSON formatting support for structured logging.
  • Contextual Logging: Add context to your logs for better traceability.

Installation

To get started with tlog, simply install it using go get:

go get github.com/phpgao/tlog

Configuration

tlog allows you to configure multiple output destinations and set log levels and formatters for each. Here's an example configuration:

package main

import (
    "github.com/phpgao/tlog"
    "net/http"
)

func main() {
    var c = []tlog.OutputConfig{
        {
            Writer:    "console",
            Level:     "info",
            Formatter: "json",
        },
        {
            Writer: "file",
            WriteConfig: tlog.WriteConfig{
                LogPath:    "/tmp/",
                Filename:   "trpc.log",
                RollType:   "size",
                MaxAge:     1,
                MaxBackups: 5,
                Compress:   false,
                MaxSize:    1024,
            },
            Level:     "debug",
            Formatter: "json",
        },
    }

    tlog.Register("default", tlog.NewZapLog(c))
    tlog.Infof("Hello, tlog!")

	tlog.SetLevel("0", tlog.LevelInfo)
}

Usage

tlog provides various methods to log messages at different levels. Here's how you can use it:

// Log an informational message
tlog.Infof("Info message: %s", "This is an info message")

// Log an error message
tlog.Errorf("Error message: %s", "This is an error message")

// Log a message with context
ctx := tlog.WithContextFields(context.TODO(), "key1", "value1", "key2", "value2")
tlog.InfoContextf(ctx, "Contextual message: %s", "This message has context")

// use RegisterHandler to set log level
mux := http.NewServeMux()
RegisterHandlerWithPath(mux, "/")
http.ListenAndServe(":8080", mux)

// gin logger
router.Use(handler.GinLogger(), gin.Recovery())

License

tlog is released under the Apache License Version 2.0.


Feel free to star and watch the repository to keep up with the latest updates!

Documentation

Overview

Package tlog provides a log for the framework and applications.

Index

Constants

View Source
const (
	OutputConsole = "console"
	OutputFile    = "file"
)

output name, default support console and file.

View Source
const (
	// WriteSync writes synchronously.
	WriteSync = 1
	// WriteAsync writes asynchronously.
	WriteAsync = 2
	// WriteFast writes fast(may drop logs asynchronously).
	WriteFast = 3
)
View Source
const (
	// RollBySize rolls logs by file size.
	RollBySize = "size"
	// RollByTime rolls logs by time.
	RollByTime = "time"
)

By which log rolls.

View Source
const (
	// TimeFormatMinute is accurate to the minute.
	TimeFormatMinute = "%Y%m%d%H%M"
	// TimeFormatHour is accurate to the hour.
	TimeFormatHour = "%Y%m%d%H"
	// TimeFormatDay is accurate to the day.
	TimeFormatDay = "%Y%m%d"
	// TimeFormatMonth is accurate to the month.
	TimeFormatMonth = "%Y%m"
	// TimeFormatYear is accurate to the year.
	TimeFormatYear = "%Y"
)

Some common used time formats.

View Source
const (
	// Minute splits by the minute.
	Minute = "minute"
	// Hour splits by the hour.
	Hour = "hour"
	// Day splits by the day.
	Day = "day"
	// Month splits by the month.
	Month = "month"
	// Year splits by the year.
	Year = "year"
)
View Source
const (
	ConsoleZapCore = "console"
	FileZapCore    = "file"
)

Some ZapCore constants.

Variables

View Source
var (
	// DefaultConsoleWriterFactory is the default console output implementation.
	DefaultConsoleWriterFactory = &ConsoleWriterFactory{}
	// DefaultFileWriterFactory is the default file output implementation.
	DefaultFileWriterFactory = &FileWriterFactory{}
)
View Source
var LevelNames = map[string]Level{
	"trace": LevelTrace,
	"debug": LevelDebug,
	"info":  LevelInfo,
	"warn":  LevelWarn,
	"error": LevelError,
	"fatal": LevelFatal,
}

LevelNames is the map from string to log level.

View Source
var LevelStrings = map[Level]string{
	LevelTrace: "trace",
	LevelDebug: "debug",
	LevelInfo:  "info",
	LevelWarn:  "warn",
	LevelError: "error",
	LevelFatal: "fatal",
}

LevelStrings is the map from log level to its string representation.

View Source
var Levels = map[string]zapcore.Level{
	"":      zapcore.DebugLevel,
	"trace": zapcore.DebugLevel,
	"debug": zapcore.DebugLevel,
	"info":  zapcore.InfoLevel,
	"warn":  zapcore.WarnLevel,
	"error": zapcore.ErrorLevel,
	"fatal": zapcore.FatalLevel,
}

Levels is the map from string to zapcore.Level.

Functions

func CustomTimeFormat

func CustomTimeFormat(t time.Time, format string) string

CustomTimeFormat customize time format. Deprecated: Use https://pkg.go.dev/time#Time.Format instead.

func Debug

func Debug(args ...interface{})

Debug logs to DEBUG log. Arguments are handled in the manner of fmt.Println.

func DebugContext

func DebugContext(ctx context.Context, args ...interface{})

DebugContext logs to DEBUG log. Arguments are handled in the manner of fmt.Println.

func DebugContextf

func DebugContextf(ctx context.Context, format string, args ...interface{})

DebugContextf logs to DEBUG log. Arguments are handled in the manner of fmt.Printf.

func Debugf

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

Debugf logs to DEBUG log. Arguments are handled in the manner of fmt.Printf.

func DefaultTimeFormat

func DefaultTimeFormat(t time.Time) []byte

DefaultTimeFormat returns the default time format "2006-01-02 15:04:05.000". Deprecated: Use https://pkg.go.dev/time#Time.AppendFormat instead.

func EnableTrace

func EnableTrace()

EnableTrace enables trace.

func Error

func Error(args ...interface{})

Error logs to ERROR log. Arguments are handled in the manner of fmt.Println.

func ErrorContext

func ErrorContext(ctx context.Context, args ...interface{})

ErrorContext logs to ERROR log. Arguments are handled in the manner of fmt.Println.

func ErrorContextf

func ErrorContextf(ctx context.Context, format string, args ...interface{})

ErrorContextf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.

func Errorf

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

Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.

func Fatal

func Fatal(args ...interface{})

Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Println. All Fatal logs will exit by calling os.Exit(1). Implementations may also call os.Exit() with a non-zero exit code.

func FatalContext

func FatalContext(ctx context.Context, args ...interface{})

FatalContext logs to ERROR log. Arguments are handled in the manner of fmt.Println. All Fatal logs will exit by calling os.Exit(1). Implementations may also call os.Exit() with a non-zero exit code.

func FatalContextf

func FatalContextf(ctx context.Context, format string, args ...interface{})

FatalContextf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.

func Fatalf

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

Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.

func GetLogEncoderKey

func GetLogEncoderKey(defKey, key string) string

GetLogEncoderKey gets user defined log output name, uses defKey if empty.

func Info

func Info(args ...interface{})

Info logs to INFO log. Arguments are handled in the manner of fmt.Println.

func InfoContext

func InfoContext(ctx context.Context, args ...interface{})

InfoContext logs to INFO log. Arguments are handled in the manner of fmt.Println.

func InfoContextf

func InfoContextf(ctx context.Context, format string, args ...interface{})

InfoContextf logs to INFO log. Arguments are handled in the manner of fmt.Printf.

func Infof

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

Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf.

func NewTimeEncoder

func NewTimeEncoder(format string) zapcore.TimeEncoder

NewTimeEncoder creates a time format encoder.

func RedirectStdLog

func RedirectStdLog(logger Logger) (func(), error)

RedirectStdLog redirects std log to trpc logger as log level INFO. After redirection, log flag is zero, the prefix is empty. The returned function may be used to recover log flag and prefix, and redirect output to os.Stderr.

func RedirectStdLogAt

func RedirectStdLogAt(logger Logger, level zapcore.Level) (func(), error)

RedirectStdLogAt redirects std log to trpc logger with a specific level. After redirection, log flag is zero, the prefix is empty. The returned function may be used to recover log flag and prefix, and redirect output to os.Stderr.

func Register

func Register(name string, logger Logger)

Register registers Logger. It supports multiple Logger implementation.

func RegisterFormatEncoder

func RegisterFormatEncoder(formatName string, newFormatEncoder NewFormatEncoder)

RegisterFormatEncoder registers a NewFormatEncoder with the specified formatName key. The existing formats include "console" and "json", but you can override these format encoders or provide a new custom one.

func RegisterWriter

func RegisterWriter(name string, writer PluginFactory)

RegisterWriter registers log output writer. Writer may have multiple implementations.

func SetLevel

func SetLevel(output string, level Level)

SetLevel sets log level for different output which may be "0", "1" or "2".

func SetLogger

func SetLogger(logger Logger)

SetLogger sets the default Logger.

func Sync

func Sync()

Sync syncs all registered loggers.

func Trace

func Trace(args ...interface{})

Trace logs to TRACE log. Arguments are handled in the manner of fmt.Println.

func TraceContext

func TraceContext(ctx context.Context, args ...interface{})

TraceContext logs to TRACE log. Arguments are handled in the manner of fmt.Println.

func TraceContextf

func TraceContextf(ctx context.Context, format string, args ...interface{})

TraceContextf logs to TRACE log. Arguments are handled in the manner of fmt.Printf.

func Tracef

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

Tracef logs to TRACE log. Arguments are handled in the manner of fmt.Printf.

func Warn

func Warn(args ...interface{})

Warn logs to WARNING log. Arguments are handled in the manner of fmt.Println.

func WarnContext

func WarnContext(ctx context.Context, args ...interface{})

WarnContext logs to WARNING log. Arguments are handled in the manner of fmt.Println.

func WarnContextf

func WarnContextf(ctx context.Context, format string, args ...interface{})

WarnContextf logs to WARNING log. Arguments are handled in the manner of fmt.Printf.

func Warnf

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

Warnf logs to WARNING log. Arguments are handled in the manner of fmt.Printf.

func WithContextFields

func WithContextFields(ctx context.Context, fields ...string) context.Context

WithContextFields sets some user defined data to logs, such as uid, imei, etc. Fields must be paired. If ctx has already set a Msg, this function returns that ctx, otherwise, it returns a new one.

Types

type Config

type Config []OutputConfig

Config is the log config. Each log may have multiple outputs.

type ConsoleWriterFactory

type ConsoleWriterFactory struct {
}

ConsoleWriterFactory is the console writer instance.

func (*ConsoleWriterFactory) Setup

func (f *ConsoleWriterFactory) Setup(name string, dec PluginDecoder) error

Setup starts, loads and registers console output writer.

func (*ConsoleWriterFactory) Type

func (f *ConsoleWriterFactory) Type() string

Type returns the log plugin type.

type Decoder

type Decoder struct {
	OutputConfig *OutputConfig
	Core         zapcore.Core
	ZapLevel     zap.AtomicLevel
}

Decoder decodes the log.

func (*Decoder) Decode

func (d *Decoder) Decode(cfg interface{}) error

Decode decodes writer configuration, copy one.

type Field

type Field struct {
	Key   string
	Value interface{}
}

Field is the user defined log field.

type FileWriterFactory

type FileWriterFactory struct {
}

FileWriterFactory is the file writer instance Factory.

func (*FileWriterFactory) Setup

func (f *FileWriterFactory) Setup(name string, dec PluginDecoder) error

Setup starts, loads and register file output writer.

func (*FileWriterFactory) Type

func (f *FileWriterFactory) Type() string

Type returns log file type.

type FormatConfig

type FormatConfig struct {
	// TimeFmt is the time format of log output, default as "2006-01-02 15:04:05.000" on empty.
	TimeFmt string `yaml:"time_fmt"`

	// TimeKey is the time key of log output, default as "T".
	TimeKey string `yaml:"time_key"`
	// LevelKey is the level key of log output, default as "L".
	LevelKey string `yaml:"level_key"`
	// NameKey is the name key of log output, default as "N".
	NameKey string `yaml:"name_key"`
	// CallerKey is the caller key of log output, default as "C".
	CallerKey string `yaml:"caller_key"`
	// FunctionKey is the function key of log output, default as "", which means not to print
	// function name.
	FunctionKey string `yaml:"function_key"`
	// MessageKey is the message key of log output, default as "M".
	MessageKey string `yaml:"message_key"`
	// StackTraceKey is the stack trace key of log output, default as "S".
	StacktraceKey string `yaml:"stacktrace_key"`
}

FormatConfig is the log format config.

type Level

type Level int

Level is the log level.

const (
	LevelNil Level = iota
	LevelTrace
	LevelDebug
	LevelInfo
	LevelWarn
	LevelError
	LevelFatal
)

Enums log level constants.

func GetLevel

func GetLevel(output string) Level

GetLevel gets log level for different output.

func (*Level) String

func (lv *Level) String() string

String turns the LogLevel to string.

type Logger

type Logger interface {
	// Trace logs to TRACE log. Arguments are handled in the manner of fmt.Println.
	Trace(args ...interface{})
	// Tracef logs to TRACE log. Arguments are handled in the manner of fmt.Printf.
	Tracef(format string, args ...interface{})
	// Debug logs to DEBUG log. Arguments are handled in the manner of fmt.Println.
	Debug(args ...interface{})
	// Debugf logs to DEBUG log. Arguments are handled in the manner of fmt.Printf.
	Debugf(format string, args ...interface{})
	// Info logs to INFO log. Arguments are handled in the manner of fmt.Println.
	Info(args ...interface{})
	// Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf.
	Infof(format string, args ...interface{})
	// Warn logs to WARNING log. Arguments are handled in the manner of fmt.Println.
	Warn(args ...interface{})
	// Warnf logs to WARNING log. Arguments are handled in the manner of fmt.Printf.
	Warnf(format string, args ...interface{})
	// Error logs to ERROR log. Arguments are handled in the manner of fmt.Println.
	Error(args ...interface{})
	// Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
	Errorf(format string, args ...interface{})
	// Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Println.
	// All Fatal logs will exit by calling os.Exit(1).
	// Implementations may also call os.Exit() with a non-zero exit code.
	Fatal(args ...interface{})
	// Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
	Fatalf(format string, args ...interface{})

	// Sync calls the underlying Core's Sync method, flushing any buffered log entries.
	// Applications should take care to call Sync before exiting.
	Sync() error

	// SetLevel sets the output log level.
	SetLevel(output string, level Level)
	// GetLevel gets the output log level.
	GetLevel(output string) Level

	// With adds user defined fields to Logger. Fields support multiple values.
	With(fields ...Field) Logger
}

Logger is the underlying logging work for tRPC framework.

var (
	// DefaultLogger the default Logger. The initial output is console. When frame start, it is
	// over write by configuration.
	DefaultLogger Logger
)

func Get

func Get(name string) Logger

Get returns the Logger implementation by log name. log.Debug use DefaultLogger to print logs. You may also use log.Get("name").Debug.

func GetDefaultLogger

func GetDefaultLogger() Logger

GetDefaultLogger gets the default Logger. To configure it, set key in configuration file to default. The console output is the default value.

func NewZapLog

func NewZapLog(c Config) Logger

NewZapLog creates a trpc default Logger from zap whose caller skip is set to 2.

func NewZapLogWithCallerSkip

func NewZapLogWithCallerSkip(cfg Config, callerSkip int) Logger

NewZapLogWithCallerSkip creates a trpc default Logger from zap.

func With

func With(fields ...Field) Logger

With adds user defined fields to Logger. Field support multiple values.

func WithContext

func WithContext(ctx context.Context, fields ...Field) Logger

WithContext add user defined fields to the Logger of context. Fields support multiple values.

type LoggerOption

type LoggerOption func(*LoggerOptions)

LoggerOption modifies the LoggerOptions.

type LoggerOptions

type LoggerOptions struct {
	LogLevel Level
	Pattern  string
	Writer   io.Writer
}

LoggerOptions is the log options.

type NewFormatEncoder

type NewFormatEncoder func(zapcore.EncoderConfig) zapcore.Encoder

NewFormatEncoder is the function type for creating a format encoder out of an encoder config.

type Option

type Option func(*options)

Option modifies the options of optionLogger.

func WithAdditionalCallerSkip

func WithAdditionalCallerSkip(skip int) Option

WithAdditionalCallerSkip adds additional caller skip.

type OptionLogger

type OptionLogger interface {
	WithOptions(opts ...Option) Logger
}

OptionLogger defines logger with additional options.

type OutputConfig

type OutputConfig struct {
	// Writer is the output of log, such as console or file.
	Writer      string      `yaml:"writer"`
	WriteConfig WriteConfig `yaml:"writer_config"`

	// Formatter is the format of log, such as console or json.
	Formatter    string       `yaml:"formatter"`
	FormatConfig FormatConfig `yaml:"formatter_config"`

	// RemoteConfig is the remote config. It's defined by business and should be registered by
	// third-party modules.
	RemoteConfig yaml.Node `yaml:"remote_config"`

	// Level controls the log level, like debug, info or error.
	Level string `yaml:"level"`

	// CallerSkip controls the nesting depth of log function.
	CallerSkip int `yaml:"caller_skip"`

	// EnableColor determines if the output is colored. The default value is false.
	EnableColor bool `yaml:"enable_color"`
}

OutputConfig is the output config, includes console, file and remote.

type PluginDecoder

type PluginDecoder interface {
	Decode(cfg interface{}) error // the input param is the custom configuration of the plugin
}

PluginDecoder is the interface used to decode plugin configuration.

type PluginFactory

type PluginFactory interface {
	// Type returns type of the plugin, i.e. selector, log, config, tracing.
	Type() string
	// Setup loads plugin by configuration.
	// The data structure of the configuration of the plugin needs to be defined in advance。
	Setup(name string, dec PluginDecoder) error
}

func GetWriter

func GetWriter(name string) PluginFactory

GetWriter gets log output writer, returns nil if not exist.

type TimeUnit

type TimeUnit string

TimeUnit is the time unit by which files are split, one of minute/hour/day/month/year.

func (TimeUnit) Format

func (t TimeUnit) Format() string

Format returns a string preceding with `.`. Use TimeFormatDay as default.

func (TimeUnit) RotationGap

func (t TimeUnit) RotationGap() time.Duration

RotationGap returns the time.Duration for time unit. Use one day as the default.

type WriteConfig

type WriteConfig struct {
	// LogPath is the log path like /usr/local/trpc/log/.
	LogPath string `yaml:"log_path"`
	// Filename is the file name like trpc.log.
	Filename string `yaml:"filename"`
	// WriteMode is the log write mod. 1: sync, 2: async, 3: fast(maybe dropped), default as 3.
	WriteMode int `yaml:"write_mode"`
	// RollType is the log rolling type. Split files by size/time, default by size.
	RollType string `yaml:"roll_type"`
	// MaxAge is the max expire times(day).
	MaxAge int `yaml:"max_age"`
	// MaxBackups is the max backup files.
	MaxBackups int `yaml:"max_backups"`
	// Compress defines whether log should be compressed.
	Compress bool `yaml:"compress"`
	// MaxSize is the max size of log file(MB).
	MaxSize int `yaml:"max_size"`

	// TimeUnit splits files by time unit, like year/month/hour/minute, default day.
	// It takes effect only when split by time.
	TimeUnit TimeUnit `yaml:"time_unit"`
}

WriteConfig is the local file config.

type WriteMode

type WriteMode int

WriteMode is the log write mode, one of 1, 2, 3.

Directories

Path Synopsis
Package handler comes from admin/admin.go of trpc-go you can add this handler to your http(s) server
Package handler comes from admin/admin.go of trpc-go you can add this handler to your http(s) server
Package rollwriter provides a high performance rolling file log.
Package rollwriter provides a high performance rolling file log.

Jump to

Keyboard shortcuts

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