utils

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package utils provides utility functions and types.

Index

Constants

This section is empty.

Variables

View Source
var NullTimer = &Timer{enabled: false, phases: make(map[string]*Phase), clock: NewRealClock()}

NullTimer is a no-op timer for when timing is disabled. All methods are safe to call but do nothing.

Functions

func SetGlobalLogger

func SetGlobalLogger(logger Logger)

SetGlobalLogger sets the global logger.

Types

type Clock

type Clock interface {
	// Now returns the current time.
	Now() time.Time

	// Since returns the duration since the given time.
	Since(t time.Time) time.Duration

	// Until returns the duration until the given time.
	Until(t time.Time) time.Duration

	// Sleep pauses the current goroutine for the specified duration.
	Sleep(d time.Duration)

	// After waits for the duration to elapse and then returns the current time on a channel.
	After(d time.Duration) <-chan time.Time

	// NewTicker creates a new Ticker that sends the current time on a channel at intervals.
	NewTicker(d time.Duration) *time.Ticker
}

Clock provides an interface for time operations, making code testable.

type DefaultLogger

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

DefaultLogger is a simple logger implementation.

func NewDefaultLogger

func NewDefaultLogger(level LogLevel, output io.Writer) *DefaultLogger

NewDefaultLogger creates a new DefaultLogger.

func NewFileLogger

func NewFileLogger(level LogLevel, logPath string) (*DefaultLogger, error)

NewFileLogger creates a logger that writes to a file.

func (*DefaultLogger) Debug

func (l *DefaultLogger) Debug(msg string, args ...interface{})

Debug logs a debug message.

func (*DefaultLogger) Error

func (l *DefaultLogger) Error(msg string, args ...interface{})

Error logs an error message.

func (*DefaultLogger) Info

func (l *DefaultLogger) Info(msg string, args ...interface{})

Info logs an info message.

func (*DefaultLogger) SetLevel

func (l *DefaultLogger) SetLevel(level LogLevel)

SetLevel sets the log level.

func (*DefaultLogger) Warn

func (l *DefaultLogger) Warn(msg string, args ...interface{})

Warn logs a warning message.

func (*DefaultLogger) WithField

func (l *DefaultLogger) WithField(key string, value interface{}) Logger

WithField creates a new logger with the given field.

func (*DefaultLogger) WithFields

func (l *DefaultLogger) WithFields(fields map[string]interface{}) Logger

WithFields creates a new logger with the given fields.

type LogLevel

type LogLevel int

LogLevel represents the severity level of a log message.

const (
	// LevelDebug is the debug log level.
	LevelDebug LogLevel = iota
	// LevelInfo is the info log level.
	LevelInfo
	// LevelWarn is the warning log level.
	LevelWarn
	// LevelError is the error log level.
	LevelError
)

func ParseLogLevel

func ParseLogLevel(level string) LogLevel

ParseLogLevel parses a string to LogLevel.

func (LogLevel) String

func (l LogLevel) String() string

String returns the string representation of LogLevel.

type Logger

type Logger interface {
	Debug(msg string, args ...interface{})
	Info(msg string, args ...interface{})
	Warn(msg string, args ...interface{})
	Error(msg string, args ...interface{})
	WithField(key string, value interface{}) Logger
	WithFields(fields map[string]interface{}) Logger
}

Logger is the interface for logging.

func GetGlobalLogger

func GetGlobalLogger() Logger

GetGlobalLogger returns the global logger.

type LoggerOutput

type LoggerOutput struct {
	Logger Logger
}

LoggerOutput adapts Logger interface to TimerOutput.

func (*LoggerOutput) Output

func (o *LoggerOutput) Output(format string, args ...interface{})

Output implements TimerOutput using Logger.Info.

type MockClock

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

MockClock implements Clock for testing purposes.

func NewMockClock

func NewMockClock(startTime time.Time) *MockClock

NewMockClock creates a new MockClock instance with the given start time.

func (*MockClock) Advance

func (c *MockClock) Advance(d time.Duration)

Advance advances the mock clock by the given duration.

func (*MockClock) After

func (c *MockClock) After(d time.Duration) <-chan time.Time

After returns a channel that receives the time after advancing.

func (*MockClock) NewTicker

func (c *MockClock) NewTicker(d time.Duration) *time.Ticker

NewTicker creates a new Ticker (for testing, this returns a real ticker).

func (*MockClock) Now

func (c *MockClock) Now() time.Time

Now returns the mock current time.

func (*MockClock) Set

func (c *MockClock) Set(t time.Time)

Set sets the mock clock to the given time.

func (*MockClock) Since

func (c *MockClock) Since(t time.Time) time.Duration

Since returns the duration since the given time using mock time.

func (*MockClock) Sleep

func (c *MockClock) Sleep(d time.Duration)

Sleep does nothing in mock clock (instant).

func (*MockClock) Until

func (c *MockClock) Until(t time.Time) time.Duration

Until returns the duration until the given time using mock time.

type NullLogger

type NullLogger struct{}

NullLogger is a logger that discards all log messages.

func (*NullLogger) Debug

func (l *NullLogger) Debug(msg string, args ...interface{})

Debug does nothing.

func (*NullLogger) Error

func (l *NullLogger) Error(msg string, args ...interface{})

Error does nothing.

func (*NullLogger) Info

func (l *NullLogger) Info(msg string, args ...interface{})

Info does nothing.

func (*NullLogger) Warn

func (l *NullLogger) Warn(msg string, args ...interface{})

Warn does nothing.

func (*NullLogger) WithField

func (l *NullLogger) WithField(key string, value interface{}) Logger

WithField returns the same NullLogger.

func (*NullLogger) WithFields

func (l *NullLogger) WithFields(fields map[string]interface{}) Logger

WithFields returns the same NullLogger.

type Phase

type Phase struct {
	Name      string
	StartTime time.Time
	EndTime   time.Time
	Duration  time.Duration
	Parent    string // Parent phase name for hierarchical display
	Level     int    // Nesting level (0 = root)
	// contains filtered or unexported fields
}

Phase represents a single timing phase with hierarchical support.

type PhaseTimer

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

PhaseTimer provides a fluent API for timing a single phase. It supports automatic completion via defer.

func (*PhaseTimer) Stop

func (pt *PhaseTimer) Stop() time.Duration

Stop stops the phase timer and records the duration. Safe to call multiple times; only the first call has effect.

type RealClock

type RealClock struct{}

RealClock implements Clock using the standard time package.

func NewRealClock

func NewRealClock() *RealClock

NewRealClock creates a new RealClock instance.

func (*RealClock) After

func (c *RealClock) After(d time.Duration) <-chan time.Time

After waits for the duration to elapse and then returns the current time on a channel.

func (*RealClock) NewTicker

func (c *RealClock) NewTicker(d time.Duration) *time.Ticker

NewTicker creates a new Ticker that sends the current time on a channel at intervals.

func (*RealClock) Now

func (c *RealClock) Now() time.Time

Now returns the current time.

func (*RealClock) Since

func (c *RealClock) Since(t time.Time) time.Duration

Since returns the duration since the given time.

func (*RealClock) Sleep

func (c *RealClock) Sleep(d time.Duration)

Sleep pauses the current goroutine for the specified duration.

func (*RealClock) Until

func (c *RealClock) Until(t time.Time) time.Duration

Until returns the duration until the given time.

type StdLogger

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

StdLogger wraps the standard library logger.

func NewStdLogger

func NewStdLogger(level LogLevel, output io.Writer) *StdLogger

NewStdLogger creates a new StdLogger.

func (*StdLogger) Debug

func (l *StdLogger) Debug(msg string, args ...interface{})

Debug logs a debug message.

func (*StdLogger) Error

func (l *StdLogger) Error(msg string, args ...interface{})

Error logs an error message.

func (*StdLogger) Info

func (l *StdLogger) Info(msg string, args ...interface{})

Info logs an info message.

func (*StdLogger) Warn

func (l *StdLogger) Warn(msg string, args ...interface{})

Warn logs a warning message.

func (*StdLogger) WithField

func (l *StdLogger) WithField(key string, value interface{}) Logger

WithField creates a new logger with the given field.

func (*StdLogger) WithFields

func (l *StdLogger) WithFields(fields map[string]interface{}) Logger

WithFields creates a new logger with the given fields.

type Timer

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

Timer is a high-cohesion, low-coupling timing utility. It supports hierarchical phases, concurrent access, and multiple output strategies.

func NewTimer

func NewTimer(name string, opts ...TimerOption) *Timer

NewTimer creates a new Timer with the given name and options.

func (*Timer) GetDuration

func (t *Timer) GetDuration(phaseName string) time.Duration

GetDuration returns the duration of a completed phase.

func (*Timer) GetPhases

func (t *Timer) GetPhases() []*Phase

GetPhases returns all phases in insertion order.

func (*Timer) PrintSummary

func (t *Timer) PrintSummary()

PrintSummary outputs the timing summary using the configured output strategy.

func (*Timer) Reset

func (t *Timer) Reset()

Reset clears all phases and resets the start time.

func (*Timer) Start

func (t *Timer) Start(phaseName string) *PhaseTimer

Start starts timing a new phase. Returns a PhaseTimer that can be used with defer for automatic completion.

func (*Timer) StartChild

func (t *Timer) StartChild(parentName, childName string) *PhaseTimer

StartChild starts timing a child phase under a parent phase. This creates hierarchical timing relationships.

func (*Timer) StopPhase

func (t *Timer) StopPhase(phaseName string) time.Duration

StopPhase stops timing a phase and returns its duration. Safe to call multiple times; only the first call has effect.

func (*Timer) Summary

func (t *Timer) Summary() string

Summary returns a formatted summary of all timing phases.

func (*Timer) TimeFunc

func (t *Timer) TimeFunc(phaseName string, fn func()) time.Duration

TimeFunc times the execution of a function and records it as a phase.

func (*Timer) TimeFuncWithError

func (t *Timer) TimeFuncWithError(phaseName string, fn func() error) (time.Duration, error)

TimeFuncWithError times the execution of a function that returns an error.

func (*Timer) ToMap

func (t *Timer) ToMap() map[string]interface{}

ToMap returns the timing data as a map for serialization.

func (*Timer) TopN

func (t *Timer) TopN(n int) []*Phase

TopN returns the top N phases by duration.

func (*Timer) TotalDuration

func (t *Timer) TotalDuration() time.Duration

TotalDuration returns the total duration since the timer was created.

type TimerOption

type TimerOption func(*Timer)

TimerOption configures a Timer instance.

func WithClock

func WithClock(clock Clock) TimerOption

WithClock sets a custom clock for testability.

func WithEnabled

func WithEnabled(enabled bool) TimerOption

WithEnabled sets whether the timer is enabled. When disabled, all operations are no-ops for zero overhead.

func WithLogger

func WithLogger(logger Logger) TimerOption

WithLogger sets a Logger as the output strategy.

func WithOutput

func WithOutput(output TimerOutput) TimerOption

WithOutput sets the output strategy for the timer.

type TimerOutput

type TimerOutput interface {
	// Output writes the timing information.
	Output(format string, args ...interface{})
}

TimerOutput defines the interface for outputting timer results. This enables dependency injection for different output strategies.

Jump to

Keyboard shortcuts

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