logger

package module
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-logger

This module is a simple and easy Golang logging module.

Quick Start

Install

go get github.com/breeze7086/go-logger

Print logs to stdout

package main

import "github.com/breeze7086/go-logger"

func main() {
  logger.SetSeverity(logger.DEBUG)
  logger.SetTimeformat("2006/01/02 15:04:05")

  logger.DebugPrintln("This is a DEBUG log")
  logger.InfoPrintln("This is an INFO log")
  logger.WarnPrintf("This is a %s log", "WARN")
  logger.ErrorPrintf("This is an %s log", "ERROR")
}

Output

Set the log level to DEBUG
file:main.go line:10 2022/03/24 11:56:11 [DEBUG] This is a DEBUG log
2022/03/24 11:56:11 [INFO] This is an INFO log
2022/03/24 11:56:11 [WARN] This is a WARN log
2022/03/24 11:56:11 [ERROR] This is an ERROR log

Change output from stdout to a file

The default logger instance uses stdout as the output location. You can create a logger instance with a custom io.Writer to write logs elsewhere.

File output

package main

import (
  "log"
  "os"

  "github.com/breeze7086/go-logger"
)

func main() {
  f, err := os.Create("test.log")
  if err != nil {
    log.Fatal(err)
  }
  defer f.Close()

  l := logger.NewLogger(logger.DEBUG, "2006-01-02 15:04:05", f)
  l.DebugPrintln("This is a DEBUG log")
  l.InfoPrintln("This is an INFO log")
}

Output

Logs will be generated in a file test.log.

$ cat test.log
file:main.go line:17 2022-03-24 13:27:07 [DEBUG] This is a DEBUG log
2022-03-24 13:27:07 [INFO] This is an INFO log

Mask sensitive values

Use Mask when you need to hide a sensitive value before printing it.

package main

import (
  "os"

  "github.com/breeze7086/go-logger"
)

func main() {
  l := logger.NewLogger(logger.INFO, "2006-01-02 15:04:05", os.Stdout)
  l.InfoPrintf("password=%s", l.Mask("secret-password"))
}

Output

2022-03-24 13:27:07 [INFO] password=******

Dump structs and maps

Use Dump to print structs, maps, slices, and arrays in a readable format. Dump uses the logger output flow, so it works with stdout, files, and other custom writers.

package main

import "github.com/breeze7086/go-logger"

type ServiceConfig struct {
  Service string
  Enabled bool
  Ports   []int
}

func main() {
  logger.Dump(ServiceConfig{
    Service: "go-logger",
    Enabled: true,
    Ports:   []int{8080, 8443},
  })

  logger.Dump(map[string]interface{}{
    "service": "go-logger",
    "enabled": true,
  })
}

Send logs to syslog

Create a logger instance and call EnableSyslog to send logs to the local logging system. If syslog is not available, the logger keeps its previous output flow.

package main

import (
  "os"

  "github.com/breeze7086/go-logger"
)

func main() {
  l := logger.NewLogger(logger.INFO, "2006-01-02 15:04:05", os.Stdout)
  l.EnableSyslog("go-logger")
  l.InfoPrintln("This log is sent to syslog when syslog is available")
}

Send logs to a Kafka topic

Create a logger instance and call EnableKafka with the bootstrap broker addresses and an existing topic. Each log entry is sent as one Kafka record, including its timestamp, severity, and trailing newline. Dump uses the same output.

package main

import (
  "log"
  "os"
  "time"

  "github.com/breeze7086/go-logger"
)

func main() {
  l := logger.NewLogger(logger.INFO, "2006-01-02 15:04:05", os.Stdout)
  writer, err := l.EnableKafka(logger.KafkaConfig{
    Brokers:  []string{"localhost:9092"},
    Topic:    "application-logs",
    ClientID: "go-logger-example",
    Timeout:  5 * time.Second,
    OnError: func(err error) {
      log.Printf("Kafka output failed: %v", err)
    },
  })
  if err != nil {
    log.Fatal(err)
  }
  defer func() {
    if err := writer.Close(); err != nil {
      log.Printf("Close Kafka output: %v", err)
    }
  }()

  l.InfoPrintf("service=%s started", "go-logger")
  l.Dump(map[string]string{"event": "ready"})
}

EnableKafka validates configuration and replaces the logger's output. Broker connections are established on the first write. Invalid configuration leaves the previous output in place. The package-level logger.EnableKafka configures the default logger; logger.NewKafkaWriter also provides an io.WriteCloser for direct use or for SetOutflow.

Writes are synchronous and wait for acknowledgements from all in-sync replicas. The default timeout is ten seconds. Publish failures are returned by KafkaWriter.Write and passed to OnError; without a callback, errors are printed to stderr. A failed or timed-out publish may still have reached the broker. There is no automatic fallback to the previous output. Call Close at shutdown to release the producer's connections, and configure output before starting concurrent logging.

For authenticated clusters, set KafkaConfig.TLS to a *tls.Config and KafkaConfig.SASLMechanism to a mechanism from github.com/segmentio/kafka-go/sasl, such as plain.Mechanism or scram.Mechanism. TLS uses Go's normal certificate validation. Kafka support uses the pure Go kafka-go v0.4.48 client to retain this module's Go 1.17 compatibility.

Set KafkaConfig.Dial when broker connections need a custom route, such as an HTTP CONNECT proxy. It opens the raw connection; the Kafka transport then performs TLS and SASL handshakes. Kafka TCP connections do not automatically use HTTP_PROXY or HTTPS_PROXY.

What's next

Feature Status
Support to mask sensitive information when do the print out ✅
Support to send logs to a Kafka topic ✅
Support to send logs to local logging system(syslog, rsyslog) ✅
Function "Dump" to gracefully print out a struct or a map ✅

Documentation

Index

Constants

View Source
const (
	DEBUG logLevel = iota
	INFO
	WARN
	ERROR
	FATAL
)

Log level constants

Variables

This section is empty.

Functions

func DebugPrintf

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

DebugPrintf std Debug printf function

func DebugPrintln

func DebugPrintln(v ...interface{})

DebugPrintln std Debug println function

func Dump added in v0.0.6

func Dump(v interface{})

Dump std function to print structs, maps, slices, and arrays in a readable format.

func ErrorPrintf

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

ErrorPrintf std Error printf function

func ErrorPrintln

func ErrorPrintln(v ...interface{})

ErrorPrintln std Error println function

func FatalPrintf

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

FatalPrintf std Fatal printf function

func FatalPrintln

func FatalPrintln(v ...interface{})

FatalPrintln std Fatal println function

func GetSeverityLevel

func GetSeverityLevel(levelName string) int8

GetSeverityLevel Get the log level constant number value from level string

func GetSeverityName

func GetSeverityName(level logLevel) string

GetSeverityName Convert the log level string to constant number value

func InfoPrintf

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

InfoPrintf std Info printf function

func InfoPrintln

func InfoPrintln(v ...interface{})

InfoPrintln std Info println function

func NewLogger

func NewLogger(level logLevel, timeformat string, outflow io.Writer) *loggerT

NewLogger New a instance of logger

func SetSeverity

func SetSeverity(level interface{})

SetSeverity Set the log level

func SetTimeformat

func SetTimeformat(timeformat string)

SetTimeformat Set the time format within log

func WarnPrintf

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

WarnPrintf std Warn printf function

func WarnPrintln

func WarnPrintln(v ...interface{})

WarnPrintln std Warn println function

Types

type KafkaConfig added in v0.0.8

type KafkaConfig struct {
	// Brokers contains bootstrap addresses in host:port form.
	Brokers []string
	// Topic must already exist in the Kafka cluster.
	Topic string
	// ClientID identifies the producer to the brokers.
	ClientID string
	// Timeout limits each publish operation. Zero uses ten seconds.
	Timeout time.Duration
	// Dial optionally opens raw broker connections, for example through a proxy.
	// The transport performs TLS and SASL handshakes after Dial returns.
	Dial func(context.Context, string, string) (net.Conn, error)
	// TLS and SASLMechanism enable encrypted and authenticated connections.
	TLS           *tls.Config
	SASLMechanism sasl.Mechanism
	// OnError receives publish errors, including writes after Close. When nil,
	// errors are printed to stderr. It may be called concurrently.
	OnError func(error)
}

KafkaConfig configures a logger's Kafka output.

type KafkaWriter added in v0.0.8

type KafkaWriter struct {
	// contains filtered or unexported fields
}

KafkaWriter publishes each nonempty Write as one Kafka record. Successful writes wait for all in-sync replicas to acknowledge the record. Use NewKafkaWriter to construct it and Close to release its connections.

func EnableKafka added in v0.0.8

func EnableKafka(config KafkaConfig) (*KafkaWriter, error)

EnableKafka configures Kafka output for the package's default logger.

func NewKafkaWriter added in v0.0.8

func NewKafkaWriter(config KafkaConfig) (*KafkaWriter, error)

NewKafkaWriter validates config and creates a synchronous Kafka writer. Connections are established on the first write, not during construction.

func (*KafkaWriter) Close added in v0.0.8

func (w *KafkaWriter) Close() error

Close waits for in-flight writes and releases the producer's connections. It is safe to call repeatedly or concurrently; later writes fail.

func (*KafkaWriter) Write added in v0.0.8

func (w *KafkaWriter) Write(p []byte) (int, error)

Write publishes p unchanged as a single record, including any trailing newline. A publish error returns zero bytes written and is also passed to OnError.

Jump to

Keyboard shortcuts

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