### Simple Logging Example Source: https://pkg.go.dev/github.com/phuslu/log A basic example demonstrating how to perform simple logging with default settings. Logs are written to os.Stderr by default. ```APIDOC ## Simple Logging Example ### Description This example shows the most basic usage of the phuslu/log library for logging messages with fields. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Request Body N/A ### Request Example ```go package main import ( "github.com/phuslu/log" ) func main() { log.Info().Str("foo", "bar").Int("number", 42).Msg("hi, phuslog") log.Info().Msgf("foo=%s number=%d error=%+v", "bar", 42, "an error") } ``` ### Response #### Success Response (200) Output is logged to standard error by default. #### Response Example ``` {"time":"2020-03-22T09:58:41.828Z","level":"info","foo":"bar","number":42,"message":"hi, phuslog"} {"time":"2020-03-22T09:58:41.828Z","level":"info","message":"foo=bar number=42 error=an error"} ``` ``` -------------------------------- ### Fiber Logger Integration Example Source: https://pkg.go.dev/github.com/phuslu/log/fiber Example demonstrating how to integrate the `phuslu/log` Fiber logger middleware into a Fiber application. It shows both default and custom logger configurations. ```APIDOC ## Usage Example This example shows how to use the `fiberlog.New` middleware for logging requests in a Fiber application. ### Default Logger Middleware ```go // Add a logger middleware, which: // - Logs all requests, like a combined access and error log. // - Logs to stdout. app.Use(fiberlog.New(&log.DefaultLogger, nil)) ``` ### Custom Logger Middleware This example configures a custom logger that writes to `access.log` and skips logging for `/backdoor` requests. ```go // Custom logger app.Use(fiberlog.New(&log.Logger{ Context: log.NewContext(nil).Str("logger", "access").Value(), Writer: &log.FileWriter{ Filename: "access.log", MaxSize: 1024 * 1024 * 1024, }, }, func(c *fiber.Ctx) bool { if string(c.Path()) == "/backdoor" { return true } return false })) ``` ### Full Example Code ```go package main import ( "fmt" "os" "time" "github.com/gofiber/fiber/v2" "github.com/phuslu/log" fiberlog "github.com/phuslu/log/fiber" ) func main() { if log.IsTerminal(os.Stderr.Fd()) { log.DefaultLogger = log.Logger{ TimeFormat: "15:04:05", Caller: 1, Writer: &log.ConsoleWriter{ ColorOutput: true, QuoteString: true, EndWithMessage: true, }, } } app := fiber.New() // Add a logger middleware, which: // - Logs all requests, like a combined access and error log. // - Logs to stdout. app.Use(fiberlog.New(&log.DefaultLogger, nil)) // Custom logger app.Use(fiberlog.New(&log.Logger{ Context: log.NewContext(nil).Str("logger", "access").Value(), Writer: &log.FileWriter{ Filename: "access.log", MaxSize: 1024 * 1024 * 1024, }, }, func(c *fiber.Ctx) bool { if string(c.Path()) == "/backdoor" { return true } return false })) app.Get("/ping", func(c *fiber.Ctx) error { return c.SendString("pong " + fmt.Sprint(time.Now().Unix())) }) app.Get("/backdoor", func(c *fiber.Ctx) error { return c.SendString("a backdoor, go away") }) log.Fatal().Err(app.Listen(":3000")).Msg("") } ``` ``` -------------------------------- ### Benchmark phuslu/slog setup Source: https://pkg.go.dev/github.com/phuslu/log Sets up and runs benchmarks for the phuslu/slog wrapper. This demonstrates how to integrate phuslu/log with slog for benchmarking. ```go func BenchmarkPhusluSlog(b *testing.B) { creator := infra.NewCreator("phuslu/slog", log.SlogNewJSONHandler, nil, `^phuslu/slog^ is a wrapper around the pre-existing ^phuslu/log^ logging library.`, map[string]string{ "phuslu/log": "https://github.com/phuslu/log", }) slogSuite := benchtests.NewSlogBenchmarkSuite(creator) benchtests.Run(b, slogSuite) } ``` -------------------------------- ### Benchmark slog.JSONHandler setup Source: https://pkg.go.dev/github.com/phuslu/log Sets up and runs benchmarks for the standard library's slog.JSONHandler. This is a baseline for performance comparisons. ```go func BenchmarkSlogJSON(b *testing.B) { slogNewJSONHandler := func(w io.Writer, options *slog.HandlerOptions) slog.Handler { return slog.NewJSONHandler(w, options) } creator := infra.NewCreator("slog/JSONHandler", slogNewJSONHandler, nil, `^slog/JSONHandler^ is the JSON handler provided with the ^slog^ library. It is fast and as a part of the Go distribution it is used along with published documentation as a model for ^slog.Handler^ behavior.`, map[string]string{ "slog/JSONHandler": "https://pkg.go.dev/log/slog#JSONHandler", }) slogSuite := benchtests.NewSlogBenchmarkSuite(creator) benchtests.Run(b, slogSuite) } ``` -------------------------------- ### Go Test Suite Setup Source: https://pkg.go.dev/github.com/phuslu/log Sets up and runs a test suite for the slog implementation. It configures warnings for duplicate entries and then executes the test suite. ```go slogSuite := verifytests.NewSlogTestSuite(creator) slogSuite.WarnOnly(warning.Duplicates) suite.Run(t, slogSuite) } ``` -------------------------------- ### NewContext Function Source: https://pkg.go.dev/github.com/phuslu/log Starts a new contextual log entry using provided destination bytes. ```go func NewContext(dst []byte) (e *Entry) ``` -------------------------------- ### Info Log Level Source: https://pkg.go.dev/github.com/phuslu/log Starts a new log message with the info level. ```go func Info() (e *Entry) ``` -------------------------------- ### Gin Logger Middleware Example Source: https://pkg.go.dev/github.com/phuslu/log-contrib/gin Demonstrates how to use the ginlogger.New middleware to integrate phuslu/log with a Gin application. Includes configuration for console and file logging, setting log levels, and a custom skip function. ```go package main import ( "fmt" "net/http" "os" "time" "github.com/gin-gonic/gin" "github.com/phuslu/log" ginlogger "github.com/phuslu/log-contrib/gin" ) func main() { if log.IsTerminal(os.Stderr.Fd()) { log.DefaultLogger = log.Logger{ TimeFormat: "15:04:05", Caller: 1, Writer: &log.ConsoleWriter{ ColorOutput: true, QuoteString: true, EndWithMessage: true, }, } } if gin.IsDebugging() { log.DefaultLogger.SetLevel(log.DebugLevel) } r := gin.New() // Custom logger r.Use(ginlogger.New( &log.Logger{ Context: log.NewContext(nil).Str("foo", "bar").Value(), Writer: &log.FileWriter{ Filename: "access.log", MaxSize: 1024 * 1024 * 1024, }, }, func(c *gin.Context) bool { if c.Request.URL.Path == "/backdoor" { return true } return false }), ) r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix())) }) r.GET("/backdoor", func(c *gin.Context) { c.String(http.StatusOK, "a backdoor, go away") }) r.Run(":8080") } ``` -------------------------------- ### Warn Log Level Source: https://pkg.go.dev/github.com/phuslu/log Starts a new log message with the warning level. ```go func Warn() (e *Entry) ``` -------------------------------- ### Trace Log Level Source: https://pkg.go.dev/github.com/phuslu/log Starts a new log message with the trace level. ```go func Trace() (e *Entry) ``` -------------------------------- ### Copy and Add Contextual Fields to Default Logger Source: https://pkg.go.dev/github.com/phuslu/log Shows how to create a sublogger by copying the default logger and adding specific contextual fields. This allows for localized context without affecting the global logger. The example demonstrates setting the level and context for a sublogger and logging messages. ```go package main import ( "github.com/phuslu/log" ) func main() { sublogger := log.DefaultLogger sublogger.Level = log.InfoLevel sublogger.Context = log.NewContext(nil).Str("ctx", "some_ctx").Value() sublogger.Debug().Int("no0", 0).Msg("zero") sublogger.Info().Int("no1", 1).Msg("first") sublogger.Info().Int("no2", 2).Msg("second") log.Debug().Int("no3", 3).Msg("no context") } ``` -------------------------------- ### Benchmark slog.Info with zerolog Source: https://pkg.go.dev/github.com/phuslu/log Benchmarks the performance of slog.Info when using zerolog's JSON handler. This setup is suitable for comparing basic logging performance. ```go func BenchmarkSlogSimpleZerolog(b *testing.B) { logger := slog.New(zeroslog.NewJsonHandler(io.Discard, &zeroslog.HandlerOptions{Level: slog.LevelInfo})) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` -------------------------------- ### Debug Log Level Source: https://pkg.go.dev/github.com/phuslu/log Starts a new log message with the debug level. ```go func Debug() (e *Entry) ``` -------------------------------- ### Log Entry Creation Functions Source: https://pkg.go.dev/github.com/phuslu/log Functions to start new log entries with different log levels. ```APIDOC ## Log Entry Creation ### Debug ```go func Debug() (e *Entry) ``` Debug starts a new message with debug level. ``` ```APIDOC ### Error ```go func Error() (e *Entry) ``` Error starts a new message with error level. ``` ```APIDOC ### Fatal ```go func Fatal() (e *Entry) ``` Fatal starts a new message with fatal level. ``` ```APIDOC ### Info ```go func Info() (e *Entry) ``` Info starts a new message with info level. ``` ```APIDOC ### NewContext ```go func NewContext(dst []byte) (e *Entry) ``` NewContext starts a new contextual entry. ``` ```APIDOC ### Panic ```go func Panic() (e *Entry) ``` Panic starts a new message with panic level. ``` ```APIDOC ### Trace ```go func Trace() (e *Entry) ``` Trace starts a new message with trace level. ``` ```APIDOC ### Warn ```go func Warn() (e *Entry) ``` Warn starts a new message with warning level. ``` -------------------------------- ### Fatal Log Level Source: https://pkg.go.dev/github.com/phuslu/log Starts a new log message with the fatal level. ```go func Fatal() (e *Entry) ``` -------------------------------- ### Fiber Logger Handler Usage Source: https://pkg.go.dev/github.com/phuslu/log/fiber Demonstrates how to integrate the phuslu/log Fiber handler for request logging. Includes setup for a default console logger and a custom file logger with conditional skipping. ```go package main import ( "fmt" "os" "time" "github.com/gofiber/fiber/v2" "github.com/phuslu/log" fiberlog "github.com/phuslu/log/fiber" ) func main() { if log.IsTerminal(os.Stderr.Fd()) { log.DefaultLogger = log.Logger{ TimeFormat: "15:04:05", Caller: 1, Writer: &log.ConsoleWriter{ ColorOutput: true, QuoteString: true, EndWithMessage: true, }, } } app := fiber.New() // Add a logger middleware, which: // - Logs all requests, like a combined access and error log. // - Logs to stdout. app.Use(fiberlog.New(&log.DefaultLogger, nil)) // Custom logger app.Use(fiberlog.New(&log.Logger{ Context: log.NewContext(nil).Str("logger", "access").Value(), Writer: &log.FileWriter{ Filename: "access.log", MaxSize: 1024 * 1024 * 1024, }, }, func(c *fiber.Ctx) bool { if string(c.Path()) == "/backdoor" { return true } return false })) app.Get("/ping", func(c *fiber.Ctx) error { return c.SendString("pong " + fmt.Sprint(time.Now().Unix())) }) app.Get("/backdoor", func(c *fiber.Ctx) error { return c.SendString("a backdoor, go away") }) log.Fatal().Err(app.Listen(":3000")).Msg("") } ``` -------------------------------- ### Replace slog.JSONHandler with phuslu/log Source: https://pkg.go.dev/github.com/phuslu/log Utilizes phuslu/log as a high-performance replacement for slog.JSONHandler. This example sets the phuslu/log handler as the default for the slog package, enabling structured JSON logging with source location information. ```go package main import ( "log/slog" "os" phuslog "github.com/phuslu/log" ) func main() { slog.SetDefault(slog.New(phuslog.SlogNewJSONHandler(os.Stderr, &slog.HandlerOptions{AddSource: true}))) slog.Info("hello from phuslu", "a", 1, "b", 2) } ``` -------------------------------- ### Add Contextual Fields with NewContext Source: https://pkg.go.dev/github.com/phuslu/log Illustrates how to add persistent key-value pairs to log entries using `log.NewContext`. This is useful for including common information like request IDs or user identifiers in all log messages within a specific scope. The example shows adding context to a logger instance. ```go logger := log.Logger{ Level: log.InfoLevel, Context: log.NewContext(nil).Str("ctx", "some_ctx").Value(), } logger.Debug().Int("no0", 0).Msg("zero") logger.Info().Int("no1", 1).Msg("first") logger.Info().Int("no2", 2).Msg("second") ``` -------------------------------- ### Initialize and use grpc logger Source: https://pkg.go.dev/github.com/phuslu/log-contrib/grpc Demonstrates how to wrap a log.Logger with grpc.New and perform logging operations. ```go import ( "github.com/phuslu/log-contrib/grpc" "github.com/phuslu/log" ) func main() { logger := grpc.New(&log.Logger{ Level: log.InfoLevel, TimeFormat: "15:04:05", Caller: 1, Writer: &log.ConsoleWriter{ ColorOutput: true, QuoteString: false, EndWithMessage: false, }, }) logger.Info("Grpc in action!", "the answer", 42) } ``` -------------------------------- ### Add Time Difference to Log Entry Source: https://pkg.go.dev/github.com/phuslu/log Use TimeDiff to add the duration between two times as a field to the log entry. If the current time is not after the start time, the duration will be 0. Requires a key, the current time, and the start time. ```go func (e *Entry) TimeDiff(key string, t time.Time, start time.Time) *Entry ``` -------------------------------- ### Create and Use logr Logger Source: https://pkg.go.dev/github.com/phuslu/log/logr Demonstrates how to create a new logr.Logger instance using a phuslog.Logger and log messages. ```go import ( "github.com/phuslu/log/logr" "github.com/phuslu/log" ) func main() { logger := logr.New(&log.Logger{ Level: log.InfoLevel, TimeFormat: "15:04:05", Caller: 1, Writer: &log.ConsoleWriter{ ColorOutput: true, QuoteString: false, EndWithMessage: false, }, }) logger.Info("Logr in action!", "the answer", 42) } ``` -------------------------------- ### Panic Log Level Source: https://pkg.go.dev/github.com/phuslu/log Starts a new log message with the panic level. ```go func Panic() (e *Entry) ``` -------------------------------- ### Implement Random Sample Logging Source: https://pkg.go.dev/github.com/phuslu/log Use Fastrandn to log only a percentage of events to reduce log volume. ```go if log.Fastrandn(100) < 5 { log.Log().Msg("hello world") } ``` -------------------------------- ### Error Log Level Source: https://pkg.go.dev/github.com/phuslu/log Starts a new log message with the error level. ```go func Error() (e *Entry) ``` -------------------------------- ### Benchmark zerolog.Info (Simple) Source: https://pkg.go.dev/github.com/phuslu/log Measures the performance of `zerolog.Info` for standard logging. Requires `github.com/rs/zerolog` and `io` imports. ```go func BenchmarkZeroLogSimple(b *testing.B) { logger := zerolog.New(io.Discard).With().Timestamp().Logger() for i := 0; i < b.N; i++ { logger.Info().Str("rate", "15").Int("low", 16).Float32("high", 123.2).Msg(msg) } } ``` -------------------------------- ### Create new TSVEntry Source: https://pkg.go.dev/github.com/phuslu/log Starts a new TSV message. This method is called on a TSVLogger instance. ```go func (l *TSVLogger) New() (e *TSVEntry) ``` -------------------------------- ### Benchmark zap.Infow (Simple) Source: https://pkg.go.dev/github.com/phuslu/log Measures the performance of `zap.Infow` for standard logging. Requires `go.uber.org/zap` and `go.uber.org/zap/zapcore` imports. ```go func BenchmarkZapSimple(b *testing.B) { logger := zap.New(zapcore.NewCore( zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), zapcore.AddSync(io.Discard), zapcore.InfoLevel, )).Sugar() for i := 0; i < b.N; i++ { logger.Infow(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` -------------------------------- ### Initialize logr Logger Source: https://pkg.go.dev/github.com/phuslu/log-contrib/logr Instantiate a new logr.Logger using a configured Phuslog logger. Ensure Phuslog is imported and configured with desired levels and output settings. ```go import ( "github.com/phuslu/log-contrib/logr" "github.com/phuslu/log" ) func main() { logger := logr.New(&log.Logger{ Level: log.InfoLevel, TimeFormat: "15:04:05", Caller: 1, Writer: &log.ConsoleWriter{ ColorOutput: true, QuoteString: false, EndWithMessage: false, }, }) logger.Info("Logr in action!", "the answer", 42) } ``` -------------------------------- ### Get counter from XID Source: https://pkg.go.dev/github.com/phuslu/log Returns the incrementing value part of the XID. This method is called on an XID value. ```go func (x XID) Counter() uint32 ``` -------------------------------- ### Benchmark slog.Info (Simple) Source: https://pkg.go.dev/github.com/phuslu/log Measures the performance of `slog.Info` for standard logging. Requires `io` and `log/slog` imports. ```go func BenchmarkSlogSimple(b *testing.B) { logger := slog.New(slog.NewJSONHandler(io.Discard, nil)) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` -------------------------------- ### Get timestamp from XID Source: https://pkg.go.dev/github.com/phuslu/log Returns the timestamp part of the XID as a time.Time object. This method is called on an XID value. ```go func (x XID) Time() time.Time ``` -------------------------------- ### Get process ID from XID Source: https://pkg.go.dev/github.com/phuslu/log Returns the process ID part of the XID. This method is called on an XID value. ```go func (x XID) Pid() uint16 ``` -------------------------------- ### Configure SyslogWriter Source: https://pkg.go.dev/github.com/phuslu/log Use SyslogWriter for memory-efficient, dependency-free syslog integration. ```go package main import ( "net" "time" "github.com/phuslu/log" ) func main() { go func() { ln, _ := net.Listen("tcp", "127.0.0.1:1601") for { conn, _ := ln.Accept() go func(c net.Conn) { b := make([]byte, 8192) n, _ := conn.Read(b) println(string(b[:n])) }(conn) } }() syslog := log.Logger{ Level: log.InfoLevel, TimeField: "ts", TimeFormat: log.TimeFormatUnixMs, Writer: &log.SyslogWriter{ Network: "tcp", // "unixgram", Address: "127.0.0.1:1601", // "/run/systemd/journal/syslog", Tag: "", Marker: "@cee:", Dial: net.Dial, }, } syslog.Info().Str("foo", "bar").Int("an", 42).Msg("a syslog info") syslog.Warn().Str("foo", "bar").Int("an", 42).Msg("a syslog warn") time.Sleep(2) } ``` -------------------------------- ### Use Stdlib Log Adapter with phuslu/log Source: https://pkg.go.dev/github.com/phuslu/log Demonstrates how to wrap a phuslu/log Logger to be compatible with Go's standard 'log' package. Ensure the Logger is configured with necessary fields like Level, TimeField, TimeFormat, Caller, Context, and Writer. ```go package main import ( stdlog "log" os "os" "github.com/phuslu/log" ) func main() { var logger *stdlog.Logger = (&log.Logger{ Level: log.InfoLevel, TimeField: "date", TimeFormat: "2006-01-02", Caller: 1, Context: log.NewContext(nil).Str("logger", "mystdlog").Int("myid", 42).Value(), Writer: &log.IOWriter{os.Stdout}, }).Std("", 0) logger.Print("hello from stdlog Print") logger.Println("hello from stdlog Println") logger.Printf("hello from stdlog %s", "Printf") } ``` -------------------------------- ### Benchmark zerolog.Info (Printf) Source: https://pkg.go.dev/github.com/phuslu/log Measures the performance of `zerolog.Info().Msgf` for formatted string logging. Requires `github.com/rs/zerolog` and `io` imports. ```go func BenchmarkZeroLogPrintf(b *testing.B) { logger := zerolog.New(io.Discard).With().Timestamp().Logger() for i := 0; i < b.N; i++ { logger.Info().Msgf("rate=%s low=%d high=%f msg=%s", "15", 16, 123.2, msg) } } ``` -------------------------------- ### Initialize GORM Logger Source: https://pkg.go.dev/github.com/phuslu/log-contrib/gorm Configures a new GORM logger instance using a phuslu/log logger and attaches it to a GORM database connection. ```go import ( "github.com/mattn/go-sqlite3" "github.com/phuslu/log" "gorm.io/gorm" gormlogger "github.com/phuslu/log-contrib/gorm" ) func main() { newLogger := gormlogger.New(&log.Logger{ Level: log.InfoLevel, TimeFormat: "15:04:05", Caller: 1, Writer: &log.ConsoleWriter{ ColorOutput: true, QuoteString: false, EndWithMessage: false, }, }) db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{Logger: newLogger}) // ... } ``` -------------------------------- ### Get machine ID from XID Source: https://pkg.go.dev/github.com/phuslu/log Returns the 3-byte machine ID part of the XID. This method is called on an XID value. ```go func (x XID) Machine() []byte ``` -------------------------------- ### Entry Dict Method Source: https://pkg.go.dev/github.com/phuslu/log Adds contextual fields from a Context as a dictionary with a specified key to the log entry. ```go func (e *Entry) Dict(key string, ctx Context) *Entry ``` -------------------------------- ### Benchmark phuslu/log slog.Info (Simple) Source: https://pkg.go.dev/github.com/phuslu/log Measures the performance of `phuslu/log`'s `slog` handler for standard logging. Requires `io` and `phuslu/log` imports. ```go func BenchmarkSlogPhusSimple(b *testing.B) { logger := slog.New(phuslog.SlogNewJSONHandler(io.Discard, nil)) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` -------------------------------- ### func New Source: https://pkg.go.dev/github.com/phuslu/log/logr Initializes a new logr.Logger instance using an existing phuslu/log.Logger configuration. ```APIDOC ## func New ### Description New returns a new logr.Logger instance that implements the logr.LogSink interface using the provided phuslu/log.Logger. ### Parameters #### Request Body - **logger** (*log.Logger) - Required - The phuslu/log logger instance to wrap. ### Response - **logr.Logger** (object) - A new logr.Logger instance. ``` -------------------------------- ### Configure Pretty Console Writer Source: https://pkg.go.dev/github.com/phuslu/log Enable human-readable, colorized output for terminal environments using ConsoleWriter. ```go if log.IsTerminal(os.Stderr.Fd()) { log.DefaultLogger = log.Logger{ TimeFormat: "15:04:05", Caller: 1, Writer: &log.ConsoleWriter{ ColorOutput: true, QuoteString: true, EndWithMessage: true, }, } } log.Debug().Int("everything", 42).Str("foo", "bar").Msg("hello world") log.Info().Int("everything", 42).Str("foo", "bar").Msg("hello world") log.Warn().Int("everything", 42).Str("foo", "bar").Msg("hello world") log.Error().Err(errors.New("an error")).Msg("hello world") ``` -------------------------------- ### Create a new grpc logger instance Source: https://pkg.go.dev/github.com/phuslu/log-contrib/grpc Wraps an existing log.Logger to provide a LoggerV2 compatible logger. ```go func New(l *log.Logger) (g *logger) ``` -------------------------------- ### func New Source: https://pkg.go.dev/github.com/phuslu/log-contrib/grpc Initializes a new gRPC logger wrapper using an existing log.Logger instance. ```APIDOC ## func New ### Description Wraps an existing log.Logger instance to provide a LoggerV2 implementation compatible with gRPC. ### Parameters - **l** (*log.Logger) - Required - The logger instance to be wrapped. ### Returns - **g** (*logger) - The initialized gRPC logger instance. ### Usage Example ```go logger := grpc.New(&log.Logger{ Level: log.InfoLevel, TimeFormat: "15:04:05", Caller: 1, Writer: &log.ConsoleWriter{ ColorOutput: true, QuoteString: false, EndWithMessage: false, }, }) logger.Info("Grpc in action!", "the answer", 42) ``` ``` -------------------------------- ### Customize Logger Fields and Format Source: https://pkg.go.dev/github.com/phuslu/log Configure the default logger or create new instances with custom time fields, formats, and output destinations. ```go package main import ( "github.com/phuslu/log" ) func main() { log.DefaultLogger = log.Logger{ Level: log.InfoLevel, Caller: 1, TimeField: "date", TimeFormat: "2006-01-02", Writer: &log.IOWriter{os.Stdout}, } log.Info().Str("foo", "bar").Msgf("hello %s", "world") logger := log.Logger{ Level: log.InfoLevel, TimeField: "ts", TimeFormat: log.TimeFormatUnixMs, } logger.Log().Str("foo", "bar").Msg("") } // Output: // {"date":"2019-07-04","level":"info","caller":"prog.go:16","foo":"bar","message":"hello world"} // {"ts":1257894000000,"foo":"bar"} ``` -------------------------------- ### Benchmark slog with zerolog groups Source: https://pkg.go.dev/github.com/phuslu/log Benchmarks slog.Info with zerolog, specifically testing the performance impact of using groups. This is useful for understanding overhead with structured logging. ```go func BenchmarkSlogGroupsZerolog(b *testing.B) { logger := slog.New(zeroslog.NewJsonHandler(io.Discard, &zeroslog.HandlerOptions{Level: slog.LevelInfo})).With("a", 1).WithGroup("g").With("b", 2) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` -------------------------------- ### Implement fiber logger middleware Source: https://pkg.go.dev/github.com/phuslu/log-contrib/fiber Demonstrates how to integrate the fiber logger middleware into a Fiber application, including default console logging and custom file-based logging with request filtering. ```go package main import ( "fmt" "os" "time" "github.com/gofiber/fiber/v2" "github.com/phuslu/log" fiberlog "github.com/phuslu/log/fiber" ) func main() { if log.IsTerminal(os.Stderr.Fd()) { log.DefaultLogger = log.Logger{ TimeFormat: "15:04:05", Caller: 1, Writer: &log.ConsoleWriter{ ColorOutput: true, QuoteString: true, EndWithMessage: true, }, } } app := fiber.New() // Add a logger middleware, which: // - Logs all requests, like a combined access and error log. // - Logs to stdout. app.Use(fiberlog.New(&log.DefaultLogger, nil)) // Custom logger app.Use(fiberlog.New(&log.Logger{ Context: log.NewContext(nil).Str("logger", "access").Value(), Writer: &log.FileWriter{ Filename: "access.log", MaxSize: 1024 * 1024 * 1024, }, }, func(c *fiber.Ctx) bool { if string(c.Path()) == "/backdoor" { return true } return false })) app.Get("/ping", func(c *fiber.Ctx) error { return c.SendString("pong " + fmt.Sprint(time.Now().Unix())) }) app.Get("/backdoor", func(c *fiber.Ctx) error { return c.SendString("a backdoor, go away") }) log.Fatal().Err(app.Listen(":3000")).Msg("") } ``` -------------------------------- ### Add Keys and Values Source: https://pkg.go.dev/github.com/phuslu/log Variadic method to add multiple keys and values to the entry. ```go func (e *Entry) KeysAndValues(keysAndValues ...any) *Entry ``` -------------------------------- ### Benchmark zerolog.Info (Caller) Source: https://pkg.go.dev/github.com/phuslu/log Measures the performance of `zerolog.Info` with caller information enabled. Requires `github.com/rs/zerolog` and `io` imports. ```go func BenchmarkZeroLogCaller(b *testing.B) { logger := zerolog.New(io.Discard).With().Caller().Timestamp().Logger() for i := 0; i < b.N; i++ { logger.Info().Str("rate", "15").Int("low", 16).Float32("high", 123.2).Msg(msg) } } ``` -------------------------------- ### Logging Entry Points Source: https://pkg.go.dev/github.com/phuslu/log Functions to initialize a new log entry at various severity levels. ```APIDOC ## Log Entry Initialization ### Description Initializes a new log entry with a specific severity level. These functions return an *Entry pointer which can then be used to add fields and finalize the message. ### Methods - Debug() - Info() - Warn() - Error() - Fatal() - Panic() - Trace() ### Usage Example ```go log.Info().Str("key", "value").Msg("hello world") ``` ``` -------------------------------- ### Log User-defined Data Structure with MarshalObject Source: https://pkg.go.dev/github.com/phuslu/log Demonstrates how to log custom Go structs effectively by implementing the `MarshalObject` interface. This allows for custom serialization of struct fields into log entries, controlling which fields are logged and how they are represented (e.g., masking sensitive data). ```go package main import ( "github.com/phuslu/log" ) type User struct { ID int Name string Pass string } func (u *User) MarshalObject(e *log.Entry) { e.Int("id", u.ID).Str("name", u.Name).Str("password", "***") } func main() { log.Info().Object("user", &User{1, "neo", "123456"}).Msg("") log.Info().EmbedObject(&User{2, "john", "abc"}).Msg("") } ``` -------------------------------- ### Benchmark slog with seankhliao groups Source: https://pkg.go.dev/github.com/phuslu/log Benchmarks slog.Info with the seankhliao handler, including the use of groups. This helps evaluate structured logging performance with this handler. ```go func BenchmarkSlogGroupsSeankhliao(b *testing.B) { logger := slog.New(seankhliao.New(slog.LevelInfo, io.Discard)).With("a", 1).WithGroup("g").With("b", 2) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` -------------------------------- ### Customize Log Writer with WriterFunc Source: https://pkg.go.dev/github.com/phuslu/log Illustrates how to use `WriterFunc` to create a custom writer that directs logs to different outputs based on their level. ```APIDOC ## Customize Log Writer with WriterFunc ### Description This example demonstrates how to use `log.WriterFunc` to create a custom log writer. This writer can conditionally send log entries to `os.Stderr` for errors or `os.Stdout` for other levels. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters #### Query Parameters N/A #### Request Body N/A ### Request Example ```go package main import ( "github.com/phuslu/log" "os" ) func main() { logger := log.Logger{ Writer: log.WriterFunc(func(e *log.Entry) (int, error) { if e.Level >= log.ErrorLevel { return os.Stderr.Write(e.Value()) } else { return os.Stdout.Write(e.Value()) } }), } logger.Info().Msg("a stdout entry") logger.Error().Msg("a stderr entry") } ``` ### Response #### Success Response (200) Logs are written to `os.Stdout` for info level and `os.Stderr` for error level. #### Response Example ``` {"time":"...","level":"info","message":"a stdout entry"} {"time":"...","level":"error","message":"a stderr entry"} ``` ``` -------------------------------- ### Benchmark zap.Infof Source: https://pkg.go.dev/github.com/phuslu/log Measures the performance of `zap.Infof` for formatted string logging. Requires `go.uber.org/zap` and `go.uber.org/zap/zapcore` imports. ```go func BenchmarkZapPrintf(b *testing.B) { logger := zap.New(zapcore.NewCore( zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), zapcore.AddSync(io.Discard), zapcore.InfoLevel, )).Sugar() for i := 0; i < b.N; i++ { logger.Infof("rate=%s low=%d high=%f msg=%s", "15", 16, 123.2, msg) } } ``` -------------------------------- ### Utility Functions Source: https://pkg.go.dev/github.com/phuslu/log Helper functions for system information and logging configuration. ```APIDOC ## Utility Functions ### Description Miscellaneous helper functions for system checks and standard output formatting. ### Functions - Fastrandn(n uint32) uint32: Returns a fast random number. - Goid() int64: Returns the current goroutine ID. - IsTerminal(fd uintptr) bool: Checks if the file descriptor is a terminal. - Printf(format string, v ...any): Standard formatted print. ``` -------------------------------- ### Perform Simple Logging Source: https://pkg.go.dev/github.com/phuslu/log Basic usage of the logger to output structured JSON logs to stderr. ```go package main import ( "github.com/phuslu/log" ) func main() { log.Info().Str("foo", "bar").Int("number", 42).Msg("hi, phuslog") log.Info().Msgf("foo=%s number=%d error=%+v", "bar", 42, "an error") } // Output: // {"time":"2020-03-22T09:58:41.828Z","level":"info","foo":"bar","number":42,"message":"hi, phuslog"} // {"time":"2020-03-22T09:58:41.828Z","level":"info","message":"foo=bar number=42 error=an error"} ``` -------------------------------- ### Benchmark zap.Infow (Any Type) Source: https://pkg.go.dev/github.com/phuslu/log Measures the performance of `zap.Infow` when logging a complex object. Requires `go.uber.org/zap` and `go.uber.org/zap/zapcore` imports. ```go func BenchmarkZapAny(b *testing.B) { logger := zap.New(zapcore.NewCore( zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), zapcore.AddSync(io.Discard), zapcore.InfoLevel, )).Sugar() for i := 0; i < b.N; i++ { logger.Infow(msg, "rate", "15", "low", 16, "object", &obj) } } ``` -------------------------------- ### Configure EventlogWriter Source: https://pkg.go.dev/github.com/phuslu/log Use EventlogWriter to log events to the Windows Event Log. ```go log.DefaultLogger.Writer = &log.EventlogWriter{ Source: ".NET Runtime", ID: 1000, } log.Info().Int("number", 42).Str("foo", "bar").Msg("hello world") ``` -------------------------------- ### Benchmark phuslu/log slog.Info (AddSource) Source: https://pkg.go.dev/github.com/phuslu/log Measures the performance of `phuslu/log`'s `slog` handler with source code location tracking enabled. Requires `io` and `phuslu/log` imports. ```go func BenchmarkSlogPhusCaller(b *testing.B) { logger := slog.New(phuslog.SlogNewJSONHandler(io.Discard, &slog.HandlerOptions{AddSource: true})) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` -------------------------------- ### func New Source: https://pkg.go.dev/github.com/phuslu/log-contrib/gin Creates a new Gin middleware handler using the provided logger and skip function. ```APIDOC ## func New ### Description Creates a new Gin middleware handler that integrates the phuslu/log logger into the Gin request pipeline. The middleware allows for a custom skip function to determine if a request should be ignored by the logger. ### Parameters - **logger** (*log.Logger) - Required - The logger instance to be used for logging requests. - **skip** (func(c *gin.Context) bool) - Required - A function that returns true if the request should be skipped by the logger. ### Returns - **gin.HandlerFunc** - The middleware handler function to be used with r.Use(). ``` -------------------------------- ### Entry Context Method Source: https://pkg.go.dev/github.com/phuslu/log Adds contextual fields from a Context to the log entry. ```go func (e *Entry) Context(ctx Context) *Entry ``` -------------------------------- ### Benchmark slog.Info (AddSource) Source: https://pkg.go.dev/github.com/phuslu/log Measures the performance of `slog.Info` with source code location tracking enabled. Requires `io` and `log/slog` imports, and `slog.HandlerOptions`. ```go func BenchmarkSlogCaller(b *testing.B) { logger := slog.New(slog.NewJSONHandler(io.Discard, &slog.HandlerOptions{AddSource: true})) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` -------------------------------- ### Entry Bytes Method Source: https://pkg.go.dev/github.com/phuslu/log Adds a byte slice field to the log entry, represented as a string. ```go func (e *Entry) Bytes(key string, val []byte) *Entry ``` -------------------------------- ### Configure Multiple IO Writer Source: https://pkg.go.dev/github.com/phuslu/log Use MultiIOWriter to write log output to multiple io.Writer targets. ```go log.DefaultLogger.Writer = &log.MultiIOWriter{ os.Stdout, &log.FileWriter{Filename: "main.log", MaxSize: 100<<20}, } log.Info().Int("number", 42).Str("foo", "bar").Msg("a info log") ``` -------------------------------- ### Configure Multiple Dispatching Writer Source: https://pkg.go.dev/github.com/phuslu/log Use MultiLevelWriter to route logs to different files based on their severity level. ```go log.DefaultLogger.Writer = &log.MultiLevelWriter{ InfoWriter: &log.FileWriter{Filename: "main.INFO", MaxSize: 100<<20}, WarnWriter: &log.FileWriter{Filename: "main.WARNING", MaxSize: 100<<20}, ErrorWriter: &log.FileWriter{Filename: "main.ERROR", MaxSize: 100<<20}, ConsoleWriter: &log.ConsoleWriter{ColorOutput: true}, ConsoleLevel: log.ErrorLevel, } log.Info().Int("number", 42).Str("foo", "bar").Msg("a info log") log.Warn().Int("number", 42).Str("foo", "bar").Msg("a warn log") log.Error().Int("number", 42).Str("foo", "bar").Msg("a error log") ``` -------------------------------- ### Test verification for phuslu/slog Source: https://pkg.go.dev/github.com/phuslu/log Sets up verification tests for the phuslu/slog wrapper. This ensures compatibility and correct behavior. ```go func TestVerifyPhusluSlog(t *testing.T) { creator := infra.NewCreator("phuslu/slog", log.SlogNewJSONHandler, nil, `^phuslu/slog^ is a wrapper around the pre-existing ^phuslu/log^ logging library.`, map[string]string{ "phuslu/log": "https://github.com/phuslu/log", }) ``` -------------------------------- ### Benchmark slog with phuslog groups Source: https://pkg.go.dev/github.com/phuslu/log Benchmarks slog.Info with the phuslog handler, including the use of groups. This tests structured logging performance with phuslog. ```go func BenchmarkSlogGroupsPhuslog(b *testing.B) { logger := slog.New((&phuslog.Logger{Writer: phuslog.IOWriter{io.Discard}}).Slog().Handler()).With("a", 1).WithGroup("g").With("b", 2) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` -------------------------------- ### Benchmark slog handler implementations Source: https://pkg.go.dev/github.com/phuslu/log Benchmark functions comparing slog handlers using standard library and zap backends. ```go func BenchmarkSlogSimpleStd(b *testing.B) { logger := slog.New(slog.NewJSONHandler(io.Discard, nil)) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` ```go func BenchmarkSlogGroupsStd(b *testing.B) { logger := slog.New(slog.NewJSONHandler(io.Discard, nil)).With("a", 1).WithGroup("g").With("b", 2) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` ```go func BenchmarkSlogSimpleZap(b *testing.B) { logcore := zapcore.NewCore( zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), zapcore.AddSync(io.Discard), zapcore.InfoLevel, ) logger := slog.New(zapslog.NewHandler(logcore)) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` ```go func BenchmarkSlogGroupsZap(b *testing.B) { logcore := zapcore.NewCore( zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), zapcore.AddSync(io.Discard), zapcore.InfoLevel, ) logger := slog.New(zapslog.NewHandler(logcore)).With("a", 1).WithGroup("g").With("b", 2) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` -------------------------------- ### Add Network Address Fields Source: https://pkg.go.dev/github.com/phuslu/log Methods for adding IP addresses and prefixes. ```go func (e *Entry) IPAddr(key string, ip net.IP) *Entry ``` ```go func (e *Entry) IPPrefix(key string, pfx net.IPNet) *Entry ``` -------------------------------- ### Benchmark slog.Info with seankhliao handler Source: https://pkg.go.dev/github.com/phuslu/log Benchmarks the performance of slog.Info using the seankhliao handler. This snippet is for comparing custom handler performance. ```go func BenchmarkSlogSimpleSeankhliao(b *testing.B) { logger := slog.New(seankhliao.New(slog.LevelInfo, io.Discard)) for i := 0; i < b.N; i++ { logger.Info(msg, "rate", "15", "low", 16, "high", 123.2) } } ``` -------------------------------- ### Marshal and Add Slice of Objects to Log Entry Source: https://pkg.go.dev/github.com/phuslu/log Use Objects to marshal a slice of objects and add them to the log entry. Requires a key and the slice of objects. ```go func (e *Entry) Objects(key string, objects any) *Entry ```