Categorygithub.com/rookie-ninja/rk-logger
modulepackage
1.2.13
Repository: https://github.com/rookie-ninja/rk-logger.git
Documentation: pkg.go.dev

# README

rk-logger

build codecov Go Report Card License

Log initializer written with golang. Currently, support zap logger as default logger and lumberjack as log rotation

Table of Contents generated with DocToc

Installation

go get -u github.com/rookie-ninja/rk-logger

Quick Start

We combined zap config and lumberjack config in the same config file Both of the configs could keep same format as it

In order to init zap logger with full log rotation, rk-logger support three different utility functions

  • With zap+lumberjack config file path
  • With zap+lumberjack config as byte array
  • With zap config and lumberjack config

With Config file path

config:

---
level: debug
encoding: console
outputPaths:
  - stdout
  - logs/rk-logger.log
errorOutputPaths:
  - stderr
initialFields:
  initFieldKey: fieldValue
encoderConfig:
  messageKey: messagea
  levelKey: level
  nameKey: logger
  timeKey: time
  callerKey: caller
  stacktraceKey: stacktrace
  callstackKey: callstack
  errorKey: error
  timeEncoder: iso8601
  fileKey: file
  levelEncoder: capital
  durationEncoder: second
  callerEncoder: full
  nameEncoder: full
  sampling:
    initial: '3'
    thereafter: '10'
maxsize: 1
maxage: 7
maxbackups: 3
localtime: true
compress: true

Example:

func NewZapLoggerWithConfPathExample() {
    // get current working directory
    dir, _ := os.Getwd()

    // init logger 
    logger, _, _ := rk_logger.NewZapLoggerWithConfPath(path.Clean(path.Join(dir, "/assets/zap.yaml")), rk_logger.YAML)
    
    // use it 
    logger.Info("NewZapLoggerWithConfPathExample")
}

With Config as byte array

Example:

func NewZapLoggerWithBytesExample() {
    bytes := []byte(`{
      "level": "debug",
      "encoding": "console",
      "outputPaths": ["stdout", "logs/rk-logger.log"],
      "errorOutputPaths": ["stderr"],
      "initialFields": {"initFieldKey": "fieldValue"},
      "encoderConfig": {
        "messageKey": "message",
        "levelKey": "level",
        "nameKey": "logger",
        "timeKey": "time",
        "callerKey": "caller",
        "stacktraceKey": "stacktrace",
        "callstackKey": "callstack",
        "errorKey": "error",
        "timeEncoder": "iso8601",
        "fileKey": "file",
        "levelEncoder": "capital",
        "durationEncoder": "second",
        "callerEncoder": "full",
        "nameEncoder": "full",
        "sampling": {
            "initial": "3",
            "thereafter": "10"
        }
      },
      "maxsize": 1,
      "maxage": 7,
      "maxbackups": 3,
      "localtime": true,
      "compress": true
    }`)

    logger, _, err := rk_logger.NewZapLoggerWithBytes(bytes, rk_logger.JSON)
    
    logger.Info("NewZapLoggerWithBytesExample")
}

With Config

func NewZapLoggerWithConfExample() {
    encodingConfig := zapcore.EncoderConfig{
        TimeKey:        "zap_timestamp",
        LevelKey:       "level",
        NameKey:        "logger",
        CallerKey:      "caller",
        MessageKey:     "msg",
        StacktraceKey:  "stacktrace",
        LineEnding:     zapcore.DefaultLineEnding,
        EncodeLevel:    zapcore.CapitalLevelEncoder,
        EncodeTime:     zapcore.ISO8601TimeEncoder,
        EncodeDuration: zapcore.SecondsDurationEncoder,
        EncodeCaller:   zapcore.ShortCallerEncoder,
    }
    
    config := &zap.Config{
        Level: zap.NewAtomicLevelAt(zap.InfoLevel),
        EncoderConfig: encodingConfig,
        OutputPaths: []string{"stdout", "logs/rk-logger.log"},
    }

    logger, _ := rk_logger.NewZapLoggerWithConf(config, &lumberjack.Logger{})
    logger.Info("NewZapLoggerWithConfExample")
}

Development Status: Stable

Contributing

We encourage and support an active, healthy community of contributors — including you! Details are in the contribution guide and the code of conduct. The rk maintainers keep an eye on issues and pull requests, but you can also report any negative conduct to [email protected].


Released under the Apache 2.0 License.

# Packages

Package main contains example of rklogger usages.

# Functions

NewLokiSyncer create new lokiSyncer.
NewLumberjackConfigDefault creates new default lumberjack config.
NewLumberjackLoggerWithBytes inits lumberjack logger as write sync with raw byte array of config file.
NewLumberjackLoggerWithConfPath inits lumberjack logger as write sync with lumberjack config file path File path needs to be absolute path.
NewZapEventConfig creates new zap.Config for EventLogger.
NewZapLoggerWithBytes inits zap logger with byte array from content of config file lumberjack.Logger could be empty, if not provided, then, we will use default write sync.
NewZapLoggerWithConf inits zap logger with config lumberjack.Logger could be empty, if not provided, then, we will use default write sync.
NewZapLoggerWithConfAndSyncer For backward compatibility with NewZapLoggerWithConf.
NewZapLoggerWithConfPath init zap logger with config file path File path needs to be absolute path lumberjack.Logger could be empty, if not provided, then, we will use default write sync.
NewZapLoggerWithOverride create new zap.Logger with override.
NewZapStdoutConfig creates new stdout config.
NewZapStdoutEncoderConfig creates new stdout encoder config.
TransformToZapConfig transforms wrapped zap config into zap.Config.
TransformToZapConfigWrap unmarshals zap.config.
WithLokiAddr provide loki address.
WithLokiClientTls provide loki http client TLS config.
WithLokiLabel provide labels, should follow isValidLabelName().
WithLokiMaxBatchSize provide max batch size.
WithLokiMaxBatchWaitMs provide max batch wait time in milli.
WithLokiPassword provide loki password.
WithLokiPath provide loki path.
WithLokiUsername provide loki username.

# Constants

EncodingConsole console encoding style of logging.
EncodingJson console encoding style of logging.
JSON https://www.json.org/.
YAML https://yaml.org/.

# Variables

Default EventLogger and EventLoggerConfig.
Default EventLogger and EventLoggerConfig.
EventLoggerConfigBytes is default zap logger which is used by EventLogger.
LumberjackConfig is default lumberjack config.
NoopLogger is default zap noop logger.
StdoutEncoderConfig is default zap logger encoder config whose output path is stdout.
StdoutLogger is default zap logger whose output path is stdout.
StdoutLoggerConfig is default zap logger config whose output path is stdout.

# Structs

LokiSyncer which will periodically send logs to Loki.
ZapConfigWrap wraps zap config which copied from zap.Config This is used while parsing zap yaml config to zap.Config with viper because Level would throw an error since it is not a type of string.
ZapEncoderConfigWrap wraps zap EncoderConfig which copied from zapcore.EncoderConfig This is used while parsing zap yaml config to zapcore.EncoderConfig with viper because Level would throw an error since it is not a type of string.

# Type aliases

FileType is a config file type which support json and yaml currently.
LokiSyncerOption options for lokiSyncer.