harelog

package module
v1.13.1 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2026 License: MIT Imports: 20 Imported by: 0

README

harelog Go

A simple and flexible Go logger for Google Cloud, with powerful context handling and developer-friendly output.


Installation

go get github.com/taknb2nch/harelog

Usage

Deprecation Notice

As of v1.11.0, the top-level constructor functions (e.g., harelog.NewTextFormatter()) have been deprecated.

They will be removed in a future major version. Please migrate to the new namespaced API (harelog.JSON, harelog.Text, harelog.Console, and harelog.Logfmt) to ensure future compatibility and to access new features like masking.

Old (Deprecated):

// DEPRECATED
fmt := harelog.NewTextFormatter()

New (Recommended):

// RECOMMENDED
fmt := harelog.Text.NewFormatter()
Basic & Structured Logging

harelog provides familiar functions for different logging styles.

import "github.com/taknb2nch/harelog"

// Simple logging (compatible with standard log package)
harelog.Println("Server is starting...")

// Formatted logging
harelog.Infof("Server started on port %d", 8080)

// Structured logging with key-value pairs
harelog.Infow("User logged in",
	"userID", "user-123",
	"ipAddress", "127.0.0.1",
)
Adding Context with the With Method (Child Loggers)

You can create a contextual logger (or "child logger") that carries a predefined set of key-value pairs. This is extremely useful for request-scoped logging, as you don't need to repeat fields like a requestID in every log call.

var logger = harelog.New() // Your base logger

func handleRequest(w http.ResponseWriter, r *http.Request) {
	// Create a new child logger with context for this specific request.
	// The base logger is not modified.
	reqLogger := logger.With("requestID", "abc-123", "remoteAddr", r.RemoteAddr)

	reqLogger.Infof("request received")
	reqLogger.Infow("user authenticated", "userID", "user-456")
}

Example Output from reqLogger:

The requestID and remoteAddr fields are automatically added to all logs.

{"message":"request received","severity":"INFO","requestID":"abc-123","remoteAddr":"127.0.0.1:12345",...}
{"message":"user authenticated","severity":"INFO","userID":"user-456","requestID":"abc-123","remoteAddr":"127.0.0.1:12345",...}

Note on Key Validation: To ensure valid structured logging, keys provided to With, ...w, or option functions (e.g., WithFields) are validated. Keys containing a space, =, or " will be ignored, and a warning will be printed to os.Stderr.

Logging with context.Context (...Ctx methods)

For integration with tracing systems, you can use the ...Ctx variants of the logging methods. harelog can automatically extract trace information from a context.Context (see Configuration section for setup).

func handleRequest(w http.ResponseWriter, r *http.Request) {
	// The request context `r.Context()` typically contains the trace header.
	logger.InfofCtx(r.Context(), "handling request")
}

Configuration

harelog provides a consistent and flexible API for configuration through three main patterns: Functional Options for New(), With... methods for deriving loggers, and SetDefault... functions for the global logger.

The most common way to configure a logger is at initialization using functional options.

// Example of a fully configured logger
logger := harelog.New(
	harelog.WithOutput(os.Stdout),
	harelog.WithLogLevel(harelog.LogLevelDebug),
	harelog.WithFormatter(harelog.NewTextFormatter()),
	harelog.WithAutoSource(harelog.SourceLocationModeAlways),
	harelog.WithPrefix("[app] "),
	harelog.WithLabels(map[string]string{"service": "api"}),
	harelog.WithFields("version", "v1.5.0"),
)
Automatic Source Code Location

For easier debugging, harelog can automatically log the file and line number of the log call site. This feature has a performance cost and is configurable via different modes.

// In production, you might only want source location for errors.
prodLogger := harelog.New(
	harelog.WithAutoSource(harelog.SourceLocationModeErrorOrAbove),
)

prodLogger.Infof("This will NOT have source info.")
prodLogger.Errorf("This WILL have source info.")
Output Formatters

harelog provides multiple formatters to suit different environments. The default is the JSONFormatter, ideal for production and log collection systems. For development, you can choose a more human-readable format.

TextFormatter

The TextFormatter provides a simple, plain-text, single-line output (e.g., TIME [LEVEL] message key=value).

// Use the WithFormatter option to switch to the plain text logger.
logger := harelog.New(
	harelog.WithFormatter(harelog.Text.NewFormatter()),
)
LogfmtFormatter

The LogfmtFormatter is a high-performance, plain-text formatter that outputs logs in the logfmt key=value format (e.g., timestamp=... severity=... message=... key=value). It is ideal for production environments that use logfmt parsers and, like TextFormatter, does not include color.

// Use the LogfmtFormatter for structured key=value text output.
logger := harelog.New(
	harelog.WithFormatter(harelog.Logfmt.NewFormatter()),
)
ConsoleFormatter (for Development)

For the ultimate developer experience, the ConsoleFormatter is designed for human-readable output, especially during local development. While the TextFormatter provides standard key-value output, the ConsoleFormatter adds log level coloring and the ability to highlight specific key-value pairs. This makes it incredibly easy to spot important information like a userID or traceID in a sea of logs.

// Use the ConsoleFormatter to highlight important keys.
formatter := harelog.Console.NewFormatter(
	// Enable coloring for log levels (e.g., [INFO] in green).
	harelog.Console.WithLogLevelColor(true),
	
	// Define your highlight rules.
	harelog.Console.WithKeyHighlight("userID", harelog.FgCyan, harelog.AttrBold),
	harelog.Console.WithKeyHighlight("requestID", harelog.FgMagenta),
	harelog.Console.WithKeyHighlight("error", harelog.FgRed, harelog.AttrUnderline),
)

logger := harelog.New(harelog.WithFormatter(formatter))

logger.Errorw("Failed to connect to database",
	"userID", "user-789",
	"requestID", "req-ghi-333",
	"error", "connection refused",
)
Dynamic Log Level Control

You can dynamically change the logger's log level at runtime using the SetLogLevel method. This operation is thread-safe and allows you to increase or decrease log verbosity (e.g., for debugging) without restarting your application.

// Start with INFO level
logger := harelog.New(harelog.WithLogLevel(harelog.LogLevelInfo))

// ... some time later, for debugging ...
logger.Info("This log is visible.")
logger.Debug("This log is NOT visible.")

// Dynamically switch to DEBUG level
logger.SetLogLevel(harelog.LogLevelDebug)

logger.Debug("This log is NOW visible.")
Default Log Level via Environment Variable

You can control the default logger's verbosity by setting the HARELOG_LEVEL environment variable.

HARELOG_LEVEL=debug go run main.go
Color Output via Environment Variables

The color output of the ConsoleFormatter can be controlled globally. This is useful for forcing color on or off in CI/CD environments or when piping output.

  • NO_COLOR or HARELOG_NO_COLOR

    • If either of these environment variables is set to any non-empty value (e.g., true, 1), color output will be disabled. This follows a quasi-standard supported by many command-line tools. HARELOG_NO_COLOR takes precedence over NO_COLOR.
  • HARELOG_FORCE_COLOR

    • If this is set to any non-empty value, color output will be forcibly enabled, even in non-TTY environments (like files or pipes).
Precedence

The variables are evaluated in the following order of priority:

  1.  HARELOG_FORCE_COLOR: If set, color is ON.
  2.  HARELOG_NO_COLOR: If set, color is OFF.
  3.  NO_COLOR: If set, color is OFF.
  4.  Default Behavior: Automatic detection based on whether the output is a TTY.
Configuring for Google Cloud Trace

To enable automatic trace extraction from a context.Context, you must provide a Project ID and the context key your application uses.

const frameworkTraceKey = "x-cloud-trace-context" 

logger := harelog.New(
	harelog.WithProjectID("my-gcp-project-id"),
	harelog.WithTraceContextKey(frameworkTraceKey),
)

Masking Sensitive Data

As a safety net, harelog formatters can be configured to automatically mask sensitive data found in Labels or Payload fields. This prevents accidental logging of passwords, API keys, or tokens.

When masking is enabled, the formatter replaces the sensitive value with the fixed-string [MASKED]. This is provided as a "zero-cost" option, meaning there is no performance impact unless you explicitly enable it.

// Configure a JSONFormatter to mask "password" (case-sensitive)
// and "authorization" (case-insensitive).
formatter := harelog.JSON.NewFormatter(
	harelog.JSON.WithMaskingKeys("password"),
	harelog.JSON.WithMaskingKeysIgnoreCase("Authorization"),
)

logger := harelog.New(harelog.WithFormatter(formatter))

// The "password" value will be masked.
logger.Infow("User login attempt",
	"user", "admin",
	"password", "secret-123", // This will be masked
)

// The "Authorization" header value will also be masked.
logger.Infow("API request",
	"Authorization", "Bearer xyz-token", // This will be masked
)

Extending with Hooks

Hooks provide a powerful way to extend harelog's functionality, turning it into a logging platform. You can use hooks to send log entries to external services like Sentry, Slack, or a custom database based on the log level.

Hook execution is fully asynchronous and panic-safe, meaning a slow or faulty hook will never impact your application's performance or stability.

Implementing a Custom Hook

To create a hook, simply implement the harelog.Hook interface.

// simple_hook.go
package main

import (
	"fmt"
	"github.com/taknb2nch/harelog"
)

// SimpleHook is a custom hook that prints to Stderr for specific levels.
type SimpleHook struct{}

// Levels specifies that this hook should only fire for Error and Critical logs.
func (h *SimpleHook) Levels() []harelog.LogLevel {
	return []harelog.LogLevel{harelog.LogLevelError, harelog.LogLevelCritical}
}

// Fire is the action to be taken when a log event matches the levels.
func (h *SimpleHook) Fire(entry *harelog.LogEntry) error {
	// Here you would typically send the entry to an external service.
	// For this example, we'll just print it.
	fmt.Fprintf(os.Stderr, "[HOOK] %s: %s\n", entry.Severity, entry.Message)
	return nil
}
Configuring Hooks

Register your custom hook at initialization using the WithHooks option.

Important: Because hooks run in the background, you must call logger.Close() (or harelog.Close() for the default logger) to ensure all buffered hook events are sent before your application exits. Using defer is the recommended approach.

// main.go
package main

import (
	"github.com/taknb2nch/harelog"
)

func main() {
	// Create an instance of your custom hook.
	myHook := &SimpleHook{}

	// Register the hook with a new logger.
	logger := harelog.New(harelog.WithHooks(myHook))

	// Ensure graceful shutdown for the hook worker.
	defer logger.Close()

	logger.Info("This will not trigger the hook.")
	logger.Error("This ERROR will trigger the hook!")
}

Special Fields

When you provide the following keys to a ...w function or the With method, the logger interprets them in a special way.

Key Type Description
error error An error object. Its message is automatically added to the log.
httpRequest *harelog.HTTPRequest For Google Cloud Logging: HTTP request information.
sourceLocation *harelog.SourceLocation For Google Cloud Logging: Source code location information.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package harelog provides a structured, level-based logging solution. It is designed to be flexible, thread-safe, and particularly well-suited for use with Google Cloud Logging by supporting its special JSON fields.

Index

Constants

View Source
const (
	// SourceLocationModeNever disables automatic source location capturing.
	// This provides the best performance. This is the default behavior.
	SourceLocationModeNever sourceLocationMode = iota

	// SourceLocationModeAlways enables automatic source location capturing for all log levels.
	// This is very useful for development and debugging, but has a performance cost.
	SourceLocationModeAlways

	// SourceLocationModeErrorOrAbove enables automatic source location capturing only for
	// logs of ERROR severity or higher. This is a balanced mode for capturing
	// critical debug information in production with minimal performance impact.
	SourceLocationModeErrorOrAbove
)

Variables

View Source
var Console = consoleOptions{}
View Source
var JSON = jsonOptions{}
View Source
var Logfmt = logfmtOptions{}
View Source
var Text = textOptions{}

Functions

func Close added in v1.7.0

func Close() error

Close gracefully shuts down the default logger's background processes, such as the hook worker. It's recommended to call this via defer in the main function to ensure all buffered logs for hooks are processed before the application exits.

func Criticalf

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

Criticalf logs a formatted message at the Critical level using the default logger.

func CriticalfCtx added in v1.4.0

func CriticalfCtx(ctx context.Context, format string, v ...interface{})

CriticalfCtx logs a formatted message at the Critical level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Criticalw

func Criticalw(msg string, kvs ...interface{})

Criticalw logs a message at the Critical level using the default logger.

func CriticalwCtx added in v1.4.0

func CriticalwCtx(ctx context.Context, msg string, kvs ...interface{})

CriticalwCtx logs a message at the Critical level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Debugf

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

Debugf logs a formatted message at the Debug level using the default logger.

func DebugfCtx added in v1.4.0

func DebugfCtx(ctx context.Context, format string, v ...interface{})

DebugfCtx logs a formatted message at the Debug level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Debugw

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

Debugw logs a message at the Debug level using the default logger.

func DebugwCtx added in v1.4.0

func DebugwCtx(ctx context.Context, msg string, kvs ...interface{})

DebugwCtx logs a message at the Debug level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Errorf

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

Errorf logs a formatted message at the Error level using the default logger.

func ErrorfCtx added in v1.4.0

func ErrorfCtx(ctx context.Context, format string, v ...interface{})

ErrorfCtx logs a formatted message at the Error level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Errorw

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

Errorw logs a message at the Error level using the default logger.

func ErrorwCtx added in v1.4.0

func ErrorwCtx(ctx context.Context, msg string, kvs ...interface{})

ErrorwCtx logs a message at the Error level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Fatal added in v1.1.0

func Fatal(v ...interface{})

Fatal logs its arguments at the Critical level and then calls os.Exit(1).

func FatalCtx added in v1.4.0

func FatalCtx(ctx context.Context, v ...interface{})

FatalCtx logs its arguments at the Critical level and then calls os.Exit(1). It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Fatalf added in v1.1.0

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

Fatalf logs a formatted message at the Critical level and then calls os.Exit(1).

func FatalfCtx added in v1.4.0

func FatalfCtx(ctx context.Context, format string, v ...interface{})

FatalfCtx logs a formatted message at the Critical level and then calls os.Exit(1). It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Fatalln added in v1.1.0

func Fatalln(v ...interface{})

Fatalln logs its arguments at the Critical level and then calls os.Exit(1).

func FatallnCtx added in v1.4.0

func FatallnCtx(ctx context.Context, v ...interface{})

FatallnCtx logs its arguments at the Critical level and then calls os.Exit(1). It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Fatalw added in v1.3.0

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

Fatalw logs a message with structured key-value pairs at the Critical level using the default logger and then calls os.Exit(1).

func FatalwCtx added in v1.4.0

func FatalwCtx(ctx context.Context, msg string, kvs ...interface{})

FatalwCtx logs a message with structured key-value pairs at the Critical level using the default logger and then calls os.Exit(1). It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Infof

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

Infof logs a formatted message at the Info level using the default logger.

func InfofCtx added in v1.4.0

func InfofCtx(ctx context.Context, format string, v ...interface{})

InfofCtx logs a formatted message at the Info level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Infow

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

Infow logs a message at the Info level using the default logger.

func InfowCtx added in v1.4.0

func InfowCtx(ctx context.Context, msg string, kvs ...interface{})

InfowCtx logs a message at the Info level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func IsCriticalEnabled

func IsCriticalEnabled() bool

IsCriticalEnabled checks if the Critical level is enabled for the default logger.

func IsDebugEnabled

func IsDebugEnabled() bool

IsDebugEnabled checks if the Debug level is enabled for the default logger.

func IsErrorEnabled

func IsErrorEnabled() bool

IsErrorEnabled checks if the Error level is enabled for the default logger.

func IsInfoEnabled

func IsInfoEnabled() bool

IsInfoEnabled checks if the Info level is enabled for the default logger.

func IsWarnEnabled

func IsWarnEnabled() bool

IsWarnEnabled checks if the Warn level is enabled for the default logger.

func NewConsoleFormatter deprecated added in v1.8.0

func NewConsoleFormatter(opts ...ConsoleFormatterOption) *consoleFormatter

Deprecated: Use harelog.Console.NewFormatter instead.

func NewJSONFormatter deprecated added in v1.2.0

func NewJSONFormatter() *jsonFormatter

Deprecated: Use harelog.JSON.NewFormatter instead.

func NewLogfmtFormatter deprecated added in v1.10.0

func NewLogfmtFormatter() *logfmtFormatter

Deprecated: Use harelog.Logfmt.NewFormatter instead.

func NewTextFormatter deprecated added in v1.2.0

func NewTextFormatter() *textFormatter

Deprecated: Use harelog.Text.NewFormatter instead.

func Print added in v1.1.0

func Print(v ...interface{})

Print logs its arguments at the Info level using the default logger.

func PrintCtx added in v1.4.0

func PrintCtx(ctx context.Context, v ...interface{})

PrintCtx logs its arguments at the Info level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Printf added in v1.1.0

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

Printf logs a formatted message at the Info level using the default logger.

func PrintfCtx added in v1.4.0

func PrintfCtx(ctx context.Context, format string, v ...interface{})

PrintfCtx logs a formatted message at the Info level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Println added in v1.1.0

func Println(v ...interface{})

Println logs its arguments at the Info level using the default logger.

func PrintlnCtx added in v1.4.0

func PrintlnCtx(ctx context.Context, v ...interface{})

PrintlnCtx logs its arguments at the Info level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func RemoveDefaultLabels

func RemoveDefaultLabels(keys ...string)

RemoveDefaultLabels removes labels from the default logger.

func SetDefaultAutoSource added in v1.6.0

func SetDefaultAutoSource(mode sourceLocationMode)

SetDefaultAutoSource sets the automatic source location capturing mode.

func SetDefaultFormatter added in v1.2.1

func SetDefaultFormatter(f Formatter)

SetDefaultFormatter sets the formatter for the default logger.

func SetDefaultHooks added in v1.7.0

func SetDefaultHooks(hooks ...Hook)

SetDefaultHooks sets hooks for the default logger. This function is safe for concurrent use. It replaces the existing default logger with a new one containing the specified hooks.

func SetDefaultLabels

func SetDefaultLabels(labels map[string]string)

SetDefaultLabels sets labels for the default logger. These labels will be included in all logs from the default logger.

func SetDefaultLogLevel

func SetDefaultLogLevel(level LogLevel)

SetDefaultLogLevel sets the log level for the default logger. The provided level should be validated with ParseLogLevel first.

func SetDefaultOutput

func SetDefaultOutput(w io.Writer)

SetDefaultOutput sets the output destination for the default logger.

func SetDefaultPrefix

func SetDefaultPrefix(prefix string)

SetDefaultPrefix sets the message prefix for the default logger.

func SetDefaultProjectID added in v1.6.0

func SetDefaultProjectID(projectID string)

WithProjectID sets the initial Google Cloud Project ID.

func SetDefaultTraceContextKey added in v1.6.0

func SetDefaultTraceContextKey(key interface{})

WithTraceContextKey sets the initial context key for tracing.

func Warnf

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

Warnf logs a formatted message at the Warn level using the default logger.

func WarnfCtx added in v1.4.0

func WarnfCtx(ctx context.Context, format string, v ...interface{})

WarnfCtx logs a formatted message at the Warn level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func Warnw

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

Warnw logs a message at the Warn level using the default logger.

func WarnwCtx added in v1.4.0

func WarnwCtx(ctx context.Context, msg string, kvs ...interface{})

WarnwCtx logs a message at the Warn level using the default logger. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

Types

type ColorAttribute added in v1.8.0

type ColorAttribute int

ColorAttribute defines a text attribute like color or style for the ConsoleFormatter.

const (
	FgBlack ColorAttribute = iota + 1
	FgRed
	FgGreen
	FgYellow
	FgBlue
	FgMagenta
	FgCyan
	FgWhite
)

Constants for foreground text colors.

const (
	AttrBold ColorAttribute = iota + 20
	AttrUnderline
)

Constants for text style attributes.

type ConsoleFormatterOption added in v1.8.0

type ConsoleFormatterOption func(*consoleFormatter)

ConsoleFormatterOption is a functional option for configuring a ConsoleFormatter.

func WithKeyHighlight deprecated added in v1.8.0

func WithKeyHighlight(key string, attrs ...ColorAttribute) ConsoleFormatterOption

Deprecated: Use harelog.Console.WithKeyHighlight instead.

func WithLogLevelColor deprecated added in v1.10.0

func WithLogLevelColor(enabled bool) ConsoleFormatterOption

Deprecated: Use harelog.Console.WithLogLevelColor instead.

type Formatter added in v1.2.0

type Formatter interface {
	Format(entry *LogEntry) ([]byte, error)
	FormatMessageOnly(entry *LogEntry) ([]byte, error)
}

Formatter is an interface for converting a logEntry into a byte slice.

type HTTPRequest

type HTTPRequest struct {
	RequestMethod string `json:"requestMethod,omitempty"`
	RequestURL    string `json:"requestUrl,omitempty"`
	Status        int    `json:"status,omitempty"`
	UserAgent     string `json:"userAgent,omitempty"`
	RemoteIP      string `json:"remoteIp,omitempty"`
	Latency       string `json:"latency,omitempty"`
}

HTTPRequest bundles information about an HTTP request for structured logging. When included in a log entry, Cloud Logging can interpret it to display request details.

type Hook added in v1.7.0

type Hook interface {
	// Levels returns the log levels that this hook should be fired for.
	// If an empty slice is returned, the hook will be fired for all levels.
	Levels() []LogLevel

	// Fire is called when a log entry is created for a level that the hook
	// is configured for. The received logEntry is a defensive copy, so modifications
	// to it will not affect other hooks or the main log output.
	Fire(entry *LogEntry) error
}

Hook is an interface that allows you to process log entries. Hooks can be used to send logs to external services like Sentry or Slack.

The Fire method will be called asynchronously in a dedicated goroutine, so it does not block the application's logging calls. Implementations of Fire must be safe for concurrent use if the hook instance is shared.

type JSONFormatterOption added in v1.11.0

type JSONFormatterOption func(f *jsonFormatter)

type LogEntry added in v1.7.0

type LogEntry struct {
	Message        string          `json:"message"`
	Severity       LogLevel        `json:"severity,omitempty"`
	Trace          string          `json:"logging.googleapis.com/trace,omitempty"`
	SpanID         string          `json:"logging.googleapis.com/spanId,omitempty"`
	TraceSampled   *bool           `json:"logging.googleapis.com/trace_sampled,omitempty"`
	HTTPRequest    *HTTPRequest    `json:"httpRequest,omitempty"`
	SourceLocation *SourceLocation `json:"logging.googleapis.com/sourceLocation,omitempty"`

	Time   time.Time         `json:"timestamp,omitempty"`
	Labels map[string]string `json:"labels,omitempty"`

	CorrelationID string `json:"correlationId,omitempty"`

	// Any fields you want to output as `jsonPayload` are stored in this map.
	Payload map[string]interface{} `json:"-"`
}

LogEntry is the internal data container for a single log entry.

func (*LogEntry) Clear added in v1.9.0

func (e *LogEntry) Clear()

type LogLevel added in v1.7.0

type LogLevel string

LogLevel defines the severity level of a log entry.

const (
	LogLevelOff      LogLevel = "OFF"
	LogLevelCritical LogLevel = "CRITICAL"
	LogLevelError    LogLevel = "ERROR"
	LogLevelWarn     LogLevel = "WARN"
	LogLevelInfo     LogLevel = "INFO"
	LogLevelDebug    LogLevel = "DEBUG"
	LogLevelAll      LogLevel = "ALL"
)

func ParseLogLevel

func ParseLogLevel(levelStr string) (LogLevel, error)

ParseLogLevel parses a string into a LogLevel. It is case-insensitive. It returns an error if the input string is not a valid log level.

type LogfmtFormatterOption added in v1.11.0

type LogfmtFormatterOption func(f *logfmtFormatter)

type Logger

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

Logger is a structured logger that provides leveled logging. Instances of Logger are safe for concurrent use.

func Clone

func Clone() *Logger

Clone creates a new copy of the default logger.

func Default added in v1.13.0

func Default() *Logger

Default returns the standard logger configured by the library.

func New

func New(opts ...Option) *Logger

New creates a new Logger with default settings. The default log level is LevelInfo and the default output is os.Stderr.

func (*Logger) Clone

func (l *Logger) Clone() *Logger

Clone creates a new copy of the logger.

func (*Logger) Close added in v1.7.0

func (l *Logger) Close() error

Close gracefully shuts down the logger's background processes, such as the hook worker. It ensures that all buffered log entries for hooks are processed before returning. It's recommended to call this via defer when the application is shutting down.

func (*Logger) Criticalf

func (l *Logger) Criticalf(format string, v ...interface{})

Criticalf logs a formatted message at the Critical level.

func (*Logger) CriticalfCtx added in v1.4.0

func (l *Logger) CriticalfCtx(ctx context.Context, format string, v ...interface{})

CriticalfCtx logs a formatted message at the Critical level. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Criticalw

func (l *Logger) Criticalw(msg string, kvs ...interface{})

Criticalw logs a message at the Critical level with structured key-value pairs.

func (*Logger) CriticalwCtx added in v1.4.0

func (l *Logger) CriticalwCtx(ctx context.Context, msg string, kvs ...interface{})

CriticalwCtx logs a formatted message at the Critical level. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Debugf

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

Debugf logs a formatted message at the Debug level.

func (*Logger) DebugfCtx added in v1.4.0

func (l *Logger) DebugfCtx(ctx context.Context, format string, v ...interface{})

DebugfCtx logs a formatted message at the Debug level. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Debugw

func (l *Logger) Debugw(msg string, kvs ...interface{})

Debugw logs a message at the Debug level with structured key-value pairs.

func (*Logger) DebugwCtx added in v1.4.0

func (l *Logger) DebugwCtx(ctx context.Context, msg string, kvs ...interface{})

DebugwCtx logs a formatted message at the Debug level. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Errorf

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

Errorf logs a formatted message at the Error level.

func (*Logger) ErrorfCtx added in v1.4.0

func (l *Logger) ErrorfCtx(ctx context.Context, format string, v ...interface{})

ErrorfCtx logs a formatted message at the Error level. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Errorw

func (l *Logger) Errorw(msg string, kvs ...interface{})

Errorw logs a message at the Error level with structured key-value pairs.

func (*Logger) ErrorwCtx added in v1.4.0

func (l *Logger) ErrorwCtx(ctx context.Context, msg string, kvs ...interface{})

ErrorwCtx logs a formatted message at the Error level. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Fatal added in v1.1.0

func (l *Logger) Fatal(v ...interface{})

Fatal logs its arguments at the Critical level and then calls os.Exit(1).

func (*Logger) FatalCtx added in v1.4.0

func (l *Logger) FatalCtx(ctx context.Context, v ...interface{})

FatalCtx logs its arguments at the Critical level and then calls os.Exit(1). It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Fatalf added in v1.1.0

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

Fatalf logs a formatted message at the Critical level and then calls os.Exit(1).

func (*Logger) FatalfCtx added in v1.4.0

func (l *Logger) FatalfCtx(ctx context.Context, format string, v ...interface{})

FatalCtxf logs a formatted message at the Critical level and then calls os.Exit(1). It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Fatalln added in v1.1.0

func (l *Logger) Fatalln(v ...interface{})

Fatalln logs its arguments at the Critical level and then calls os.Exit(1).

func (*Logger) FatallnCtx added in v1.4.0

func (l *Logger) FatallnCtx(ctx context.Context, v ...interface{})

FatallnCtx logs its arguments at the Critical level and then calls os.Exit(1). It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Fatalw added in v1.3.0

func (l *Logger) Fatalw(msg string, kvs ...interface{})

Fatalw logs a message with structured key-value pairs at the Critical level and then calls os.Exit(1).

func (*Logger) FatalwCtx added in v1.4.0

func (l *Logger) FatalwCtx(ctx context.Context, msg string, kvs ...interface{})

FatalwCtx logs a message with structured key-value pairs at the Critical level and then calls os.Exit(1). It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Infof

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

Infof logs a formatted message at the Info level.

func (*Logger) InfofCtx added in v1.4.0

func (l *Logger) InfofCtx(ctx context.Context, format string, v ...interface{})

InfofCtx logs a formatted message at the Info level. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Infow

func (l *Logger) Infow(msg string, kvs ...interface{})

Infow logs a message at the Info level with structured key-value pairs.

func (*Logger) InfowCtx added in v1.4.0

func (l *Logger) InfowCtx(ctx context.Context, msg string, kvs ...interface{})

InfowCtx logs a formatted message at the Info level. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) IsCriticalEnabled

func (l *Logger) IsCriticalEnabled() bool

IsCriticalEnabled checks if the Critical level is enabled for the logger.

func (*Logger) IsDebugEnabled

func (l *Logger) IsDebugEnabled() bool

IsDebugEnabled checks if the Debug level is enabled for the logger.

func (*Logger) IsErrorEnabled

func (l *Logger) IsErrorEnabled() bool

IsErrorEnabled checks if the Error level is enabled for the logger.

func (*Logger) IsInfoEnabled

func (l *Logger) IsInfoEnabled() bool

IsInfoEnabled checks if the Info level is enabled for the logger.

func (*Logger) IsWarnEnabled

func (l *Logger) IsWarnEnabled() bool

IsWarnEnabled checks if the Warn level is enabled for the logger.

func (*Logger) Print added in v1.1.0

func (l *Logger) Print(v ...interface{})

Print logs its arguments at the Info level, like log.Print.

func (*Logger) PrintCtx added in v1.4.0

func (l *Logger) PrintCtx(ctx context.Context, v ...interface{})

PrintCtx logs its arguments at the Info level, like log.Print. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Printf added in v1.1.0

func (l *Logger) Printf(format string, v ...interface{})

Printf logs a formatted message at the Info level, like log.Printf.

func (*Logger) PrintfCtx added in v1.4.0

func (l *Logger) PrintfCtx(ctx context.Context, format string, v ...interface{})

PrintfCtx logs a formatted message at the Info level, like log.Printf. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Println added in v1.1.0

func (l *Logger) Println(v ...interface{})

Println logs its arguments at the Info level, like log.Println.

func (*Logger) PrintlnCtx added in v1.4.0

func (l *Logger) PrintlnCtx(ctx context.Context, v ...interface{})

PrintlnCtx logs its arguments at the Info level, like log.Println. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) SetLogLevel added in v1.12.0

func (l *Logger) SetLogLevel(level LogLevel)

SetLogLevel dynamically updates the logger's log level. This operation is thread-safe.

func (*Logger) Warnf

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

Warnf logs a formatted message at the Warn level.

func (*Logger) WarnfCtx added in v1.4.0

func (l *Logger) WarnfCtx(ctx context.Context, format string, v ...interface{})

WarnfCtx logs a formatted message at the Warn level. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) Warnw

func (l *Logger) Warnw(msg string, kvs ...interface{})

Warnw logs a message at the Warn level with structured key-value pairs.

func (*Logger) WarnwCtx added in v1.4.0

func (l *Logger) WarnwCtx(ctx context.Context, msg string, kvs ...interface{})

WarnwCtx logs a formatted message at the Warn level. It extracts values from the provided context, such as Google Cloud Trace identifiers, and includes them in the log entry.

func (*Logger) With added in v1.4.0

func (l *Logger) With(kvs ...interface{}) *Logger

With returns a new logger instance with the provided key-value pairs added to its context. It panics if the number of arguments is odd or if a key is not a string.

func (*Logger) WithAutoSource added in v1.6.0

func (l *Logger) WithAutoSource(mode sourceLocationMode) *Logger

WithAutoSource returns a new logger with a different source location mode.

func (*Logger) WithCorrelationID

func (l *Logger) WithCorrelationID(correlationID string) *Logger

WithCorrelationID returns a new logger instance with the specified correlation ID.

func (*Logger) WithFormatter added in v1.2.1

func (l *Logger) WithFormatter(f Formatter) *Logger

WithFormatter returns a new logger instance with the specified formatter.

func (*Logger) WithLabels

func (l *Logger) WithLabels(labels map[string]string) *Logger

WithLabels returns a new logger instance with the provided labels added.

func (*Logger) WithLogLevel

func (l *Logger) WithLogLevel(level LogLevel) *Logger

WithLogLevel returns a new logger instance with the specified log level.

func (*Logger) WithOutput

func (l *Logger) WithOutput(w io.Writer) *Logger

WithOutput returns a new logger instance that writes to the provided io.Writer.

func (*Logger) WithPrefix

func (l *Logger) WithPrefix(prefix string) *Logger

WithPrefix returns a new logger instance with the specified message prefix.

func (*Logger) WithProjectID added in v1.6.0

func (l *Logger) WithProjectID(projectID string) *Logger

WithProjectID returns a new logger with a different Project ID.

func (*Logger) WithSpanId

func (l *Logger) WithSpanId(spanId string) *Logger

WithSpanId returns a new logger instance with the specified GCP spanId identifier.

func (*Logger) WithTrace

func (l *Logger) WithTrace(trace string) *Logger

WithTrace returns a new logger instance with the specified GCP trace identifier.

func (*Logger) WithTraceContextKey added in v1.6.0

func (l *Logger) WithTraceContextKey(key interface{}) *Logger

WithTraceContextKey returns a new logger with a different trace context key.

func (*Logger) WithTraceSampled

func (l *Logger) WithTraceSampled(traceSampled *bool) *Logger

WithTraceSampled returns a new logger instance with the specified GCP traceSampled identifier.

func (*Logger) WithoutLabels

func (l *Logger) WithoutLabels(keys ...string) *Logger

WithoutLabels returns a new logger instance with the provided labels removed.

type Option added in v1.2.0

type Option func(*Logger)

Option configures a Logger.

func WithAutoSource added in v1.5.0

func WithAutoSource(mode sourceLocationMode) Option

WithAutoSource is a functional option that configures the logger's behavior for automatically capturing the source code location (file, line, function name). Note: Enabling this feature, especially with SourceLocationModeAlways, has a non-trivial performance cost due to the use of runtime.Callers.

func WithFields added in v1.6.0

func WithFields(kvs ...interface{}) Option

WithFields sets the initial set of contextual key-value fields (payload).

func WithFormatter added in v1.2.0

func WithFormatter(f Formatter) Option

WithFormatter sets the formatter for the logger.

func WithHookBufferSize added in v1.7.0

func WithHookBufferSize(size int) Option

WithHookBufferSize sets the buffer size for the hook channel. The default is 100. A larger buffer can handle higher log volumes without dropping hook events, but consumes more memory.

func WithHooks added in v1.7.0

func WithHooks(hooks ...Hook) Option

WithHooks is a functional option that registers hooks with the logger. Hooks are triggered asynchronously when a log entry is created at a level specified in the hook's Levels() method.

func WithLabels added in v1.6.0

func WithLabels(labels map[string]string) Option

WithLabels sets the initial set of labels.

func WithLogLevel added in v1.5.0

func WithLogLevel(level LogLevel) Option

WithLogLevel is a functional option that sets the initial log level for the logger.

func WithOutput added in v1.2.0

func WithOutput(w io.Writer) Option

WithOutput sets the writer for the logger.

func WithPrefix added in v1.6.0

func WithPrefix(prefix string) Option

WithPrefix sets the initial message prefix.

func WithProjectID added in v1.4.0

func WithProjectID(id string) Option

WithProjectID sets the Google Cloud Project ID to be used for formatting trace identifiers.

func WithTraceContextKey added in v1.4.0

func WithTraceContextKey(key interface{}) Option

WithTraceContextKey sets the key used to extract Google Cloud Trace data from a context.Context.

type SourceLocation

type SourceLocation struct {
	File     string `json:"file,omitempty"`
	Line     int    `json:"line,omitempty"`
	Function string `json:"function,omitempty"`
}

SourceLocation represents the location in the source code where a log entry was generated.

type TextFormatterOption added in v1.4.0

type TextFormatterOption func(*textFormatter)

TextFormatterOption is a functional option for configuring a TextFormatter.

Directories

Path Synopsis
examples
formatter command
This program demonstrates the advanced features of the ConsoleFormatter.
This program demonstrates the advanced features of the ConsoleFormatter.
hooks command
simple command
examples/main.go
examples/main.go

Jump to

Keyboard shortcuts

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