log

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2023 License: MIT Imports: 11 Imported by: 5

README

Project myproject

Introduction

This project aims to provide a lightweight logging framework that supports multiple logging formats and output methods. It includes the following features:

  • Built-in formatters: supports JSON and text formatting output methods.
  • Extensible output methods: supports output to console, file, ELK, and other methods.
  • Configurable log levels: supports setting different levels of log information for easy troubleshooting.
  • Optional stack information: supports outputting call stack information for easy troubleshooting.

Features

This framework supports the following features:

  • Supports multiple log levels: Trace, Debug, Info, Warn, Error, Fatal, Panic.
  • Supports multiple output methods: Console, File, ELK.
  • Supports multiple formatting methods: JSON, Text.
  • Supports asynchronous log writing.
  • Supports printing all environment variables at startup.
  • Supports dynamically setting log levels.
  • Supports outputting stack information.

Getting Started

Prerequisites

This project requires Go 2.0 or higher.

Building

You can build the example program by running the following command in the project root directory:

$ make build
Running

You can run the example program by running the following command in the project root directory:

$ ./bin/main

Usage

Import the framework as follows:

import "github.com/kubecub/log"
Code Examples
package main

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

func main() {
    // Create a Logger instance
    logger := cuslog.NewLogger(cuslog.WithLevel(cuslog.InfoLevel))

    // Output log information
    logger.Info("Info message")

    // Output log information with fields
    logger.WithFields(cuslog.Fields{
        "animal": "walrus",
        "size":   10,
    }).Info("A group of walrus emerges from the ocean")
}

Contributing

Contributions to this project are welcome! Please see CONTRIBUTING.md for details.

Community (Optional)

Join our community! You can find us on the following channels:

Author

License

This project is licensed under the MIT License.

Documentation

Index

Constants

View Source
const (
	KeyRequestID   keylogger = "requestID"
	KeyUsername    keylogger = "username"
	KeyWatcherName keylogger = "watcher"
)

Defines common log fields.

Variables

View Source
var (
	// DebugLevel logs are typically voluminous, and are usually disabled in
	// production.
	DebugLevel = zapcore.DebugLevel // iota - 1
	// InfoLevel is the default logging priority.
	InfoLevel = zapcore.InfoLevel
	// WarnLevel logs are more important than Info, but don't need individual
	// human review.
	WarnLevel = zapcore.WarnLevel
	// ErrorLevel logs are high-priority. If an application is running smoothly,
	// it shouldn't generate any error-level logs.
	ErrorLevel = zapcore.ErrorLevel
	// DPanicLevel logs are particularly important errors. In development the
	// logger panics after writing the message.
	DPanicLevel = zapcore.DPanicLevel
	// PanicLevel logs a message, then panics.
	PanicLevel = zapcore.PanicLevel
	// FatalLevel logs a message, then calls os.Exit(1).
	FatalLevel = zapcore.FatalLevel
)

Define the basic log level. Alias for zap level type const.

View Source
var (
	Any         = zap.Any         // accepts a field key and an arbitrary value
	Array       = zap.Array       // accepts a field key and an ArrayMarshaler
	Bool        = zap.Bool        // accepts a field key and a bool
	Boolp       = zap.Boolp       // accepts a field key and a *bool
	Bools       = zap.Bools       // accepts a field key and a []bool
	ByteString  = zap.ByteString  // accepts a field key and a ByteString
	ByteStrings = zap.ByteStrings // accepts a field key and a []ByteString
	Binary      = zap.Binary      // accepts a field key and []byte
	Complex128  = zap.Complex128  // accepts a field key and a complex128
	Complex128p = zap.Complex128p // accepts a field key and a *complex128
	Complex128s = zap.Complex128s // accepts a field key and a []complex128
	Complex64   = zap.Complex64   // accepts a field key and a complex64
	Complex64p  = zap.Complex64p  // accepts a field key and a *complex64
	Complex64s  = zap.Complex64s  // accepts a field key and a []complex64
	Duration    = zap.Duration    // accepts a field key and a time.Duration
	Durationp   = zap.Durationp   // accepts a field key and a *time.Duration
	Durations   = zap.Durations   // accepts a field key and a []time.Duration
	Err         = zap.Error       // accepts a field key and an error
	Errors      = zap.Errors      // accepts a field key and a []error
	Float32     = zap.Float32     // accepts a field key and a float32
	Float32p    = zap.Float32p    // accepts a field key and a *float32
	Float32s    = zap.Float32s    // accepts a field key and a []float32
	Float64     = zap.Float64     // accepts a field key and a float64
	Float64p    = zap.Float64p    // accepts a field key and a *float64
	Float64s    = zap.Float64s    // accepts a field key and a []float64
	Int         = zap.Int         // accepts a field key and an int
	Intp        = zap.Intp        // accepts a field key and a *int
	Ints        = zap.Ints        // accepts a field key and a []int
	Int64       = zap.Int64       // accepts a field key and an int64
	Int64p      = zap.Int64p      // accepts a field key and a *int64
	Int64s      = zap.Int64s      // accepts a field key and a []int64
	Int32       = zap.Int32       // accepts a field key and an int32
	Int32p      = zap.Int32p      // accepts a field key and a *int32
	Int32s      = zap.Int32s      // accepts a field key and a []int32
	Int16       = zap.Int16       // accepts a field key and an int16
	Int16p      = zap.Int16p      // accepts a field key and a *int16
	Int16s      = zap.Int16s      // accepts a field key and a []int16
	Int8        = zap.Int8        // accepts a field key and an int8
	Int8p       = zap.Int8p       // accepts a field key and a *int8
	Int8s       = zap.Int8s       // accepts a field key and a []int8
	Namespace   = zap.Namespace   // accepts a field key and returns a new logger that is a child of the current logger and adds a namespace to the field key
	Object      = zap.Object      // accepts a field key and an ObjectMarshaler
	Reflect     = zap.Reflect     // accepts a field key and an arbitrary value, and reflects on the value to create more fields
	Skip        = zap.Skip        // accepts no arguments and is a no-op
	String      = zap.String      // accepts a field key and a string
	Stringp     = zap.Stringp     // accepts a field key and a *string
	Strings     = zap.Strings     // accepts a field key and a []string
	Stringer    = zap.Stringer    // accepts a field key and a fmt.Stringer
	Time        = zap.Time        // accepts a field key and a time.Time
	Timep       = zap.Timep       // accepts a field key and a *time.Time
	Times       = zap.Times       // accepts a field key and a []time.Time
	Uint        = zap.Uint        // accepts a field key and a uint
	Uintp       = zap.Uintp       // accepts a field key and a *uint
	Uints       = zap.Uints       // accepts a field key and a []uint
	Uint64      = zap.Uint64      // accepts a field key and a uint64
	Uint64p     = zap.Uint64p     // accepts a field key and a *uint64
	Uint64s     = zap.Uint64s     // accepts a field key and a []uint64
	Uint32      = zap.Uint32      // accepts a field key and a uint32
	Uint32p     = zap.Uint32p     // accepts a field key and a *uint32
	Uint32s     = zap.Uint32s     // accepts a field key and a []uint32
	Uint16      = zap.Uint16      // accepts a field key and a uint16
	Uint16p     = zap.Uint16p     // accepts a field key and a *uint16
	Uint16s     = zap.Uint16s     // accepts a field key and a []uint16
	Uint8       = zap.Uint8       // accepts a field key and a uint8
	Uint8p      = zap.Uint8p      // accepts a field key and a *uint8
	Uint8s      = zap.Uint8s      // accepts a field key and a []uint8
	Uintptr     = zap.Uintptr     // accepts a field key and a uintptr
	Uintptrp    = zap.Uintptrp    // accepts a field key and a *uintptr
	Uintptrs    = zap.Uintptrs    // accepts a field key and a []uintptr
)

Alias for zap type functions.

Functions

func CheckIntLevel

func CheckIntLevel(level int32) bool

CheckIntLevel used for other log wrapper such as klog which return if logging a message at the specified level is enabled.

func Debug

func Debug(msg string, fields ...Field)

Debug method output debug level log.

func Debugf

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

Debugf method output debug level log.

func Debugw

func Debugw(msg string, keysAndValues ...interface{})

Debugw method output debug level log.

func Error

func Error(msg string, fields ...Field)

Error method output error level log.

func Errorf

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

Errorf method output error level log.

func Errorw

func Errorw(msg string, keysAndValues ...interface{})

Errorw method output error level log.

func Fatal

func Fatal(msg string, fields ...Field)

Fatal method output fatal level log.

func Fatalf

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

Fatalf method output fatal level log.

func Fatalw

func Fatalw(msg string, keysAndValues ...interface{})

Fatalw method output Fatalw level log.

func Flush

func Flush()

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

func Info

func Info(msg string, fields ...Field)

--------------------------------------------------- Info method output info level log.

func Infof

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

Infof method output info level log.

func Infow

func Infow(msg string, keysAndValues ...interface{})

Infow method output info level log.

func Init

func Init(opts *Options)

Init initializes logger with specified options.

func L

func L(ctx context.Context) *zapLogger

L method output with specified context value.

func New

func New(opts *Options) *zapLogger

New create logger by opts which can custmoized by command arguments.

func Panic

func Panic(msg string, fields ...Field)

Panic method output panic level log and shutdown application.

func Panicf

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

Panicf method output panic level log and shutdown application.

func Panicw

func Panicw(msg string, keysAndValues ...interface{})

Panicw method output panic level log.

func StdErrLogger

func StdErrLogger() *log.Logger

StdErrLogger returns logger of standard library which writes to supplied zap logger at error level.

func StdInfoLogger

func StdInfoLogger() *log.Logger

StdInfoLogger returns logger of standard library which writes to supplied zap logger at info level.

func SugaredLogger

func SugaredLogger() *zap.SugaredLogger

SugaredLogger returns global sugared logger.

func Warn

func Warn(msg string, fields ...Field)

Warn method output warning level log.

func Warnf

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

Warnf method output warning level log.

func Warnw

func Warnw(msg string, keysAndValues ...interface{})

Warnw method output warning level log.

func WithContext

func WithContext(ctx context.Context) context.Context

WithContext returns a copy of context in which the log value is set.

func ZapLogger

func ZapLogger() *zap.Logger

ZapLogger used for other log wrapper such as klog.

Types

type Field

type Field = zapcore.Field

Field is an alias for the field structure in the underlying log frame. The Field type is used to add key-value pairs to a logger's context in Go, with most fields being lazily marshaled to make it inexpensive to add fields to disabled debug-level log statements.

type InfoLogger

type InfoLogger interface {
	// Info logs a non-error message with the given key/value pairs as context.
	//
	// The msg argument should be used to add some constant description to
	// the log line.  The key/value pairs can then be used to add additional
	// variable information.  The key/value pairs should alternate string
	// keys and arbitrary values.
	Info(msg string, fields ...Field)
	Infof(format string, v ...interface{})
	Infow(msg string, keysAndValues ...interface{})

	// Enabled tests whether this InfoLogger is enabled.  For example,
	// commandline flags might be used to set the logging verbosity and disable
	// some info logs.
	Enabled() bool
}

InfoLogger represents the ability to log non-error messages, at a particular verbosity.

func V

func V(level Level) InfoLogger

V return a leveled InfoLogger.

type Level

type Level = zapcore.Level

Level is an alias for the level structure in the underlying log frame. A Level is a logging priority. Higher levels are more important.

type Logger

type Logger interface {
	// All Loggers implement InfoLogger.  Calling InfoLogger methods directly on
	// a Logger value is equivalent to calling them on a V(0) InfoLogger.  For
	// example, logger.Info() produces the same result as logger.V(0).Info.
	InfoLogger
	Debug(msg string, fields ...Field)
	Debugf(format string, v ...interface{})
	Debugw(msg string, keysAndValues ...interface{})
	Warn(msg string, fields ...Field)
	Warnf(format string, v ...interface{})
	Warnw(msg string, keysAndValues ...interface{})
	Error(msg string, fields ...Field)
	Errorf(format string, v ...interface{})
	Errorw(msg string, keysAndValues ...interface{})
	Panic(msg string, fields ...Field)
	Panicf(format string, v ...interface{})
	Panicw(msg string, keysAndValues ...interface{})
	Fatal(msg string, fields ...Field)
	Fatalf(format string, v ...interface{})
	Fatalw(msg string, keysAndValues ...interface{})

	// V returns an InfoLogger value for a specific verbosity level.  A higher
	// verbosity level means a log message is less important.  It's illegal to
	// pass a log level less than zero.
	V(level Level) InfoLogger
	Write(p []byte) (n int, err error)

	// WithValues adds some key-value pairs of context to a logger.
	// See Info for documentation on how key/value pairs work.
	WithValues(keysAndValues ...interface{}) Logger

	// WithName adds a new element to the logger's name.
	// Successive calls with WithName continue to append
	// suffixes to the logger's name.  It's strongly recommended
	// that name segments contain only letters, digits, and hyphens
	// (see the package documentation for more information).
	WithName(name string) Logger

	// WithContext returns a copy of context in which the log value is set.
	WithContext(ctx context.Context) context.Context

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

Logger represents the ability to log messages, both errors and not.

func FromContext

func FromContext(ctx context.Context) Logger

FromContext returns the value of the log key on the ctx.

func NewLogger

func NewLogger(l *zap.Logger) Logger

NewLogger creates a new logr.Logger using the given Zap Logger to log.

func WithName

func WithName(s string) Logger

WithName adds a new path segment to the logger's name. Segments are joined by periods. By default, Loggers are unnamed.

func WithValues

func WithValues(keysAndValues ...interface{}) Logger

WithValues creates a child logger and adds adds Zap fields to it.

type Options

type Options struct {
	OutputPaths       []string `json:"output-paths"       mapstructure:"output-paths"`
	ErrorOutputPaths  []string `json:"error-output-paths" mapstructure:"error-output-paths"`
	Level             string   `json:"level"              mapstructure:"level"`
	Format            string   `json:"format"             mapstructure:"format"`
	DisableCaller     bool     `json:"disable-caller"     mapstructure:"disable-caller"`
	DisableStacktrace bool     `json:"disable-stacktrace" mapstructure:"disable-stacktrace"`
	EnableColor       bool     `json:"enable-color"       mapstructure:"enable-color"`
	Development       bool     `json:"development"        mapstructure:"development"`
	Name              string   `json:"name"               mapstructure:"name"`
}

Options contains configuration items related to log.

func NewOptions

func NewOptions() *Options

NewOptions creates an Options object with default parameters.

func (*Options) AddFlags

func (o *Options) AddFlags(fs *pflag.FlagSet)

AddFlags adds flags for log to the specified FlagSet object.

func (*Options) Build

func (o *Options) Build() error

Build constructs a global zap logger from the Config and Options.

func (*Options) String

func (o *Options) String() string

func (*Options) Validate

func (o *Options) Validate() []error

Validate validate the options fields.

Directories

Path Synopsis
cuslog module
Package distribution implements a logger which compatible to logrus/std log/prometheus.
Package distribution implements a logger which compatible to logrus/std log/prometheus.
example module
Package klog init klog logger.
Package klog init klog logger.
logrus module

Jump to

Keyboard shortcuts

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