log

package
v0.1.13 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Example

Example demonstrates the two usage modes of this package.

Stdout mode: call InitLog with no arguments for stdout output at INFO level. File mode: call InitLog once at startup with a Config, and defer Close to flush all buffered entries before the process exits.

package main

import (
	"github.com/phcp-tech/common-library-golang/log"
)

func main() {
	log.InitLog(&log.Config{
		Level:      "info",
		FilePath:   "/var/log/app.log",
		MaxSizeMB:  100,
		MaxBackups: 7,
		MaxAgeDays: 30,
		Compress:   true,
	})
	defer log.Close()

	log.Info("application started")
	log.InfoWith("request handled",
		"method", "GET",
		"path", "/api/v1/users",
		"status", 200,
	)
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Close added in v0.1.4

func Close()

Close flushes all pending async log entries and closes the underlying rotating log file. It should be called during graceful shutdown. No-op when logging to stdout.

Example

ExampleClose shows that Close should be deferred immediately after InitLog. It flushes the async ring buffer and closes the underlying rotating file. It is a no-op when the logger writes to stdout.

package main

import (
	"github.com/phcp-tech/common-library-golang/log"
)

func main() {
	log.InitLog(&log.Config{
		Level:    "info",
		FilePath: "/var/log/app.log",
	})
	defer log.Close()

	log.Info("shutting down")
}

func Debug

func Debug(msg string)

Debug logs a message at DEBUG level using the singleton logger.

func DebugWith

func DebugWith(msg string, args ...any)

DebugWith logs a message at DEBUG level with additional structured key-value fields. args must be alternating key-value pairs, e.g. DebugWith("msg", "key", value).

Example

ExampleDebugWith shows how to attach structured context to a debug log entry. args must alternate between a string key and its value; mismatched pairs are handled gracefully by the underlying slog handler.

package main

import (
	"github.com/phcp-tech/common-library-golang/log"
)

func main() {
	log.DebugWith("cache lookup",
		"key", "user:42",
		"hit", false,
		"duration_us", 38,
	)
}

func Debugf

func Debugf(format string, args ...any)

Debugf logs a formatted message at DEBUG level using the singleton logger.

func Error

func Error(msg string)

Error logs a message at ERROR level using the singleton logger.

func ErrorWith

func ErrorWith(msg string, args ...any)

ErrorWith logs a message at ERROR level with additional structured key-value fields. args must be alternating key-value pairs, e.g. ErrorWith("msg", "key", value).

Example

ExampleErrorWith shows how to attach error context and diagnostics to an error log entry.

package main

import (
	"github.com/phcp-tech/common-library-golang/log"
)

func main() {
	log.ErrorWith("database query failed",
		"table", "orders",
		"duration_ms", 1523,
		"error", "connection timeout",
	)
}

func Errorf

func Errorf(format string, args ...any)

Errorf logs a formatted message at ERROR level using the singleton logger.

func Info

func Info(msg string)

Info logs a message at INFO level using the singleton logger.

Example

ExampleInfo shows basic message logging to stdout. InitLog must always be called before any log function.

package main

import (
	"github.com/phcp-tech/common-library-golang/log"
)

func main() {
	log.InitLog() // stdout + INFO
	log.Info("application started")
}

func InfoWith

func InfoWith(msg string, args ...any)

InfoWith logs a message at INFO level with additional structured key-value fields. args must be alternating key-value pairs, e.g. InfoWith("msg", "key", value).

Example

ExampleInfoWith shows structured logging with additional key-value context. args must alternate between a string key and its value; mismatched pairs are handled gracefully by the underlying slog handler.

package main

import (
	"github.com/phcp-tech/common-library-golang/log"
)

func main() {
	log.InfoWith("user login",
		"user_id", 42,
		"ip", "192.168.1.1",
		"success", true,
	)
}

func Infof

func Infof(format string, args ...any)

Infof logs a formatted message at INFO level using the singleton logger.

func InitLog added in v0.1.1

func InitLog(cfg ...*Config)

InitLog configures the logger. It must be called once at application startup before any log function (Debug/Info/Warn/Error and their variants). Subsequent calls have no effect (only the first call takes effect). If called with no arguments, or with a nil Config pointer, the logger writes to stdout at INFO level. Pass a non-nil Config with FilePath set to enable rotating file logging. InitLog calls slog.SetDefault so that all subsequent slog.* calls and stdlib log.Print / log.Printf calls are routed through the configured handler.

Example (File)

ExampleInitLog_file shows file logging mode: pass a *Config with FilePath set. For stdout at default INFO level, InitLog need not be called at all. To customise level without file output, use InitLog(&log.Config{Level: "debug"}).

package main

import (
	"github.com/phcp-tech/common-library-golang/log"
)

func main() {
	log.InitLog(&log.Config{
		Level:      "info",
		FilePath:   "/var/log/app.log",
		MaxSizeMB:  100,  // rotate after 100 MB
		MaxBackups: 7,    // keep at most 7 backup files
		MaxAgeDays: 30,   // delete backups older than 30 days; 0 = never delete
		Compress:   true, // gzip rotated files to save disk space
	})
	defer log.Close()

	log.Info("file logging enabled")
}

func SetLevel

func SetLevel(level string) error

SetLevel dynamically changes the log level of the singleton logger. Accepted values are "error", "warn", "info", and "debug" (case-insensitive). Returns an error if the provided level string is unrecognised.

Example

ExampleSetLevel shows how to change the active log level at runtime without restarting the application. It also demonstrates the error returned for an unrecognised level string.

package main

import (
	"fmt"

	"github.com/phcp-tech/common-library-golang/log"
)

func main() {
	_ = log.SetLevel("debug") // enable verbose output temporarily
	_ = log.SetLevel("info")  // restore normal level

	if err := log.SetLevel("invalid"); err != nil {
		fmt.Println(err)
	}
}
Output:
unknown log level: invalid

func Warn

func Warn(msg string)

Warn logs a message at WARN level using the singleton logger.

func WarnWith

func WarnWith(msg string, args ...any)

WarnWith logs a message at WARN level with additional structured key-value fields. args must be alternating key-value pairs, e.g. WarnWith("msg", "key", value).

Example

ExampleWarnWith shows how to attach structured context to a warning entry.

package main

import (
	"github.com/phcp-tech/common-library-golang/log"
)

func main() {
	log.WarnWith("rate limit approaching",
		"user_id", 99,
		"requests", 980,
		"limit", 1000,
	)
}

func Warnf

func Warnf(format string, args ...any)

Warnf logs a formatted message at WARN level using the singleton logger.

Types

type Config added in v0.1.1

type Config struct {
	Level      string // "debug"|"info"|"warn"|"error"; default "info"
	FilePath   string // if non-empty, enables rotating file logging
	MaxSizeMB  int    // max size of a single log file in MB; default 100
	MaxBackups int    // max number of rotated backup files to retain; default 100
	MaxAgeDays int    // max age in days before deletion; 0 means never delete
	Compress   bool   // compress rotated files with gzip
}

Config holds all configuration for the logger. Call InitLog with a Config before the first log call. If FilePath is empty, logs are written to stdout.

Directories

Path Synopsis
Package component provides log lifecycle integration for bootstrap.
Package component provides log lifecycle integration for bootstrap.

Jump to

Keyboard shortcuts

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