Documentation
¶
Overview ¶
Example ¶
Example demonstrates basic usage of the logger
package main
import (
"bytes"
"fmt"
"github.com/pdat-cz/golog"
"strings"
)
func main() {
// Create a buffer to capture output
var buf bytes.Buffer
// Create a logger with the buffer as output
opts := golog.Options{
Writer: &buf,
Level: golog.InfoLevel,
}
log := golog.New(opts)
// Log messages at different levels
log.Info().Msg("This is an info message")
log.Warn().Msg("This is a warning message")
log.Error().Msg("This is an error message")
// Verify that messages were logged
output := buf.String()
fmt.Println("Info message logged:", strings.Contains(output, "info"))
fmt.Println("Warn message logged:", strings.Contains(output, "warn"))
fmt.Println("Error message logged:", strings.Contains(output, "error"))
}
Output: Info message logged: true Warn message logged: true Error message logged: true
Index ¶
- type Event
- func (e *Event) Any(key string, val interface{}) *Event
- func (e *Event) Bool(key string, val bool) *Event
- func (e *Event) Duration(key string, val time.Duration) *Event
- func (e *Event) Err(err error) *Event
- func (e *Event) Hex(key string, val []byte) *Event
- func (e *Event) Int(key string, val int) *Event
- func (e *Event) Msg(msg string)
- func (e *Event) Str(key, val string) *Event
- func (e *Event) Time(key string, val time.Time) *Event
- type Hook
- type Level
- type Logger
- func (l *Logger) AddHook(hook Hook) *Logger
- func (l *Logger) Debug() *Event
- func (l *Logger) Error() *Event
- func (l *Logger) Fatal() *Event
- func (l *Logger) GetLevel() Level
- func (l *Logger) Info() *Event
- func (l *Logger) RemoveHook(hook Hook) *Logger
- func (l *Logger) SetLevel(level Level)
- func (l *Logger) Warn() *Event
- func (l *Logger) With(key string, value interface{}) *Logger
- type NatsConn
- type NatsHook
- type Options
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Event ¶
type Event struct {
// contains filtered or unexported fields
}
Event represents a log event
func (*Event) Bool ¶
Bool adds a boolean field to the event
Example ¶
ExampleEvent_Bool demonstrates adding boolean fields to log events
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/pdat-cz/golog"
)
func main() {
// Create a buffer to capture output
var buf bytes.Buffer
// Create a logger with the buffer as output
opts := golog.Options{
Writer: &buf,
Level: golog.InfoLevel,
}
log := golog.New(opts)
// Add boolean fields to the log event
log.Info().
Bool("cache_hit", true).
Bool("authenticated", false).
Msg("Cache status")
// Parse the JSON to verify fields
var entry map[string]interface{}
json.Unmarshal(buf.Bytes(), &entry)
// Print the relevant fields
fmt.Println("Message:", entry["message"])
fmt.Println("Cache hit:", entry["cache_hit"])
fmt.Println("Authenticated:", entry["authenticated"])
}
Output: Message: Cache status Cache hit: true Authenticated: false
func (*Event) Err ¶
Err adds an error field to the event
Example ¶
ExampleEvent_Err demonstrates adding error fields to log events
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/pdat-cz/golog"
)
func main() {
// Create a buffer to capture output
var buf bytes.Buffer
// Create a logger with the buffer as output
opts := golog.Options{
Writer: &buf,
Level: golog.InfoLevel,
}
log := golog.New(opts)
// Create an error
err := errors.New("connection refused")
// Add the error to the log event
log.Error().
Err(err).
Str("server", "db-01").
Msg("Database connection failed")
// Parse the JSON to verify fields
var entry map[string]interface{}
json.Unmarshal(buf.Bytes(), &entry)
// Print the relevant fields
fmt.Println("Message:", entry["message"])
fmt.Println("Error:", entry["error"])
fmt.Println("Server:", entry["server"])
}
Output: Message: Database connection failed Error: connection refused Server: db-01
func (*Event) Int ¶
Int adds an integer field to the event
Example ¶
ExampleEvent_Int demonstrates adding integer fields to log events
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/pdat-cz/golog"
)
func main() {
// Create a buffer to capture output
var buf bytes.Buffer
// Create a logger with the buffer as output
opts := golog.Options{
Writer: &buf,
Level: golog.InfoLevel,
}
log := golog.New(opts)
// Add integer fields to the log event
log.Info().
Int("status_code", 200).
Int("response_time_ms", 45).
Msg("Request completed")
// Parse the JSON to verify fields
var entry map[string]interface{}
json.Unmarshal(buf.Bytes(), &entry)
// Print the relevant fields
fmt.Println("Message:", entry["message"])
fmt.Println("Status code:", int(entry["status_code"].(float64)))
fmt.Println("Response time (ms):", int(entry["response_time_ms"].(float64)))
}
Output: Message: Request completed Status code: 200 Response time (ms): 45
func (*Event) Str ¶
Str adds a string field to the event
Example ¶
ExampleEvent_Str demonstrates adding string fields to log events
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/pdat-cz/golog"
)
func main() {
// Create a buffer to capture output
var buf bytes.Buffer
// Create a logger with the buffer as output
opts := golog.Options{
Writer: &buf,
Level: golog.InfoLevel,
}
log := golog.New(opts)
// Add string fields to the log event
log.Info().
Str("service", "user-service").
Str("method", "GetUser").
Msg("User retrieved successfully")
// Parse the JSON to verify fields
var entry map[string]interface{}
json.Unmarshal(buf.Bytes(), &entry)
// Print the relevant fields
fmt.Println("Message:", entry["message"])
fmt.Println("Service:", entry["service"])
fmt.Println("Method:", entry["method"])
}
Output: Message: User retrieved successfully Service: user-service Method: GetUser
type Hook ¶
type Hook interface {
// Fire is called when a log event occurs
Fire(entry map[string]interface{}) error
// Levels returns the log levels this hook should be triggered for
Levels() []Level
}
Hook represents a log hook that processes log entries
type Level ¶
type Level int8
Level represents logging level
func ParseLevel ¶
ParseLevel parses a level string into a Level value
Example ¶
ExampleParseLevel demonstrates parsing a level string into a Level value
package main
import (
"fmt"
"github.com/pdat-cz/golog"
)
func main() {
// Parse level strings
debugLevel := golog.ParseLevel("debug")
infoLevel := golog.ParseLevel("info")
warnLevel := golog.ParseLevel("warn")
errorLevel := golog.ParseLevel("error")
fatalLevel := golog.ParseLevel("fatal")
unknownLevel := golog.ParseLevel("unknown")
// Print the levels
fmt.Println("Debug level:", debugLevel)
fmt.Println("Info level:", infoLevel)
fmt.Println("Warn level:", warnLevel)
fmt.Println("Error level:", errorLevel)
fmt.Println("Fatal level:", fatalLevel)
fmt.Println("Unknown level (defaults to info):", unknownLevel)
}
Output: Debug level: debug Info level: info Warn level: warn Error level: error Fatal level: fatal Unknown level (defaults to info): info
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger represents the core logger structure
func New ¶
New creates a new logger with the given options
Example ¶
ExampleNew demonstrates creating a logger with custom options
package main
import (
"bytes"
"fmt"
"github.com/pdat-cz/golog"
"strings"
)
func main() {
// Create a buffer to capture output
var buf bytes.Buffer
// Create custom options
opts := golog.Options{
Writer: &buf,
Level: golog.InfoLevel,
}
// Create a new logger with custom options
log := golog.New(opts)
// Log messages
log.Debug().Msg("This debug message won't be logged due to level setting")
log.Info().Msg("This info message will be logged")
// Verify the debug message was filtered out and info was logged
output := buf.String()
fmt.Println("Debug message logged:", strings.Contains(output, "debug"))
fmt.Println("Info message logged:", strings.Contains(output, "info"))
}
Output: Debug message logged: false Info message logged: true
func NewConsoleLogger ¶
func NewConsoleLogger() *Logger
NewConsoleLogger creates a new logger with console output
func (*Logger) AddHook ¶
AddHook adds a hook to the logger
Example ¶
ExampleLogger_AddHook demonstrates adding a hook to the logger
package main
import (
"bytes"
"fmt"
"github.com/pdat-cz/golog"
)
// PrintHook is a simple hook that captures log entries
type PrintHook struct {
levels []golog.Level
lastEntry map[string]interface{}
}
// Fire is called when a log event occurs
func (h *PrintHook) Fire(entry map[string]interface{}) error {
h.lastEntry = entry
return nil
}
// Levels returns the log levels this hook should be triggered for
func (h *PrintHook) Levels() []golog.Level {
return h.levels
}
func main() {
// Create a buffer to capture output
var buf bytes.Buffer
// Create a logger with the buffer as output
opts := golog.Options{
Writer: &buf,
Level: golog.InfoLevel,
}
log := golog.New(opts)
// Create and add a hook that only fires for error and fatal levels
hook := &PrintHook{
levels: []golog.Level{golog.ErrorLevel, golog.FatalLevel},
}
log.AddHook(hook)
// This won't trigger the hook
log.Info().Msg("This is an info message")
// This will trigger the hook
log.Error().Msg("This is an error message")
// Verify the hook was triggered for error but not info
fmt.Println("Hook triggered for error level:", hook.lastEntry != nil)
if hook.lastEntry != nil {
fmt.Println("Hook received message:", hook.lastEntry["message"])
}
}
Output: Hook triggered for error level: true Hook received message: This is an error message
func (*Logger) RemoveHook ¶
RemoveHook removes a hook from the logger
func (*Logger) With ¶
With returns a new logger with the given field added to its context
Example ¶
ExampleLogger_With demonstrates using contextual logging
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/pdat-cz/golog"
)
func main() {
// Create a buffer to capture output
var buf bytes.Buffer
// Create a logger with the buffer as output
opts := golog.Options{
Writer: &buf,
Level: golog.InfoLevel,
}
log := golog.New(opts)
// Create a logger with context fields
requestLogger := log.With("request_id", "req-123456").With("user_id", "user-789")
// Log a message with the context fields
requestLogger.Info().Msg("Processing request")
// Parse the JSON to verify fields
var entry map[string]interface{}
json.Unmarshal(buf.Bytes(), &entry)
// Print the relevant fields
fmt.Println("Message:", entry["message"])
fmt.Println("Request ID:", entry["request_id"])
fmt.Println("User ID:", entry["user_id"])
}
Output: Message: Processing request Request ID: req-123456 User ID: user-789