### Simple Console Logging Setup Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/handler.md This example demonstrates the basic setup for console logging by creating a logger, adding a console handler for all log levels, and logging an info message. ```go logger := slog.New() h := handler.NewConsoleHandler(slog.AllLevels) logger.AddHandler(h) logger.Info("message") ``` -------------------------------- ### Full Slog Logger Setup Example Source: https://github.com/gookit/slog/blob/master/_autodocs/GUIDE.md This example demonstrates how to set up a comprehensive logger with console and file handlers, rotation, compression, and custom processors. It also shows how to use sub-loggers for contextual logging. ```go package main import ( "context" "github.com/gookit/slog" "github.com/gookit/slog/handler" "github.com/gookit/rotatefile" ) func setupLogger() *slog.Logger { logger := slog.NewWithName("myapp") // Console handler console := handler.NewConsoleHandler(slog.AllLevels) f := slog.NewTextFormatter() f.EnableColor = true console.SetFormatter(f) logger.AddHandler(console) // File handler for errors errorFile, err := handler.NewFileHandler( "/var/log/myapp-error.log", handler.WithLogLevels(slog.DangerLevels), ) if err != nil { panic(err) } logger.AddHandler(errorFile) // Rotating file handler appFile, err := handler.NewRotateFileHandler( "/var/log/myapp.log", rotatefile.EveryDay, handler.WithCompress(true), handler.WithBackupNum(30), ) if err != nil { panic(err) } logger.AddHandler(appFile) // Add processors logger.AddProcessor(slog.AddHostname()) logger.AddProcessor(slog.ProcessorFunc(func(r *slog.Record) { r.AddField("env", "production") })) return logger } func main() { logger := setupLogger() defer logger.Close() logger.Info("application started") // Simulate request handling ctx := context.Background() sl := slog.NewSubWith(logger). KeepCtx(ctx). KeepFields(slog.M{ "endpoint": "/api/users", "method": "POST", }) defer sl.Release() sl.Info("request received") sl.WithData(slog.M{ "user_id": 123, "action": "create", }).Info("creating resource") sl.Info("request completed") } ``` -------------------------------- ### Complete SugaredLogger Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md A comprehensive example demonstrating the setup, configuration, and usage of SugaredLogger. It covers quick setup, deferred closing, level configuration, formatter customization, and various logging methods including structured data. ```go package main import ( "github.com/gookit/slog" ) func main() { // Quick setup logger := slog.NewStdLogger() defer logger.Close() // Configure logger.Config(func(sl *slog.SugaredLogger) { sl.Level = slog.InfoLevel f := slog.AsTextFormatter(sl.Formatter) f.SetTemplate("[{{level}}] {{message}}\n") }) // Use logger.Info("application started") logger.Infof("version: %s", "1.0.0") logger.WithData(slog.M{ "module": "auth", "user": "john", }).Info("user logged in") logger.Warn("this is a warning") logger.Error("this is an error") } ``` -------------------------------- ### Install slog Source: https://github.com/gookit/slog/blob/master/_autodocs/GUIDE.md Install the slog library using go get. ```bash go get github.com/gookit/slog ``` -------------------------------- ### Comprehensive Error Handling Example Source: https://github.com/gookit/slog/blob/master/_autodocs/errors.md This example demonstrates a complete setup for logging with multiple handlers, including file and console outputs, with robust error checking at each stage. It ensures proper logger closure and flushing. ```go package main import ( "errors" "fmt" "log" "os" "github.com/gookit/slog" "github.com/gookit/slog/handler" "github.com/gookit/rotatefile" ) func setupLogger() (*slog.Logger, error) { logger := slog.New() // Try to create file handlers errorH, err := handler.NewFileHandler( "/var/log/myapp-error.log", handler.WithLogLevels(slog.DangerLevels), ) if err != nil { return nil, fmt.Errorf("error handler: %w", err) } defer func() { if err != nil { _ = errorH.Close() } }() rotateH, err := handler.NewRotateFileHandler( "/var/log/myapp.log", rotatefile.EveryDay, handler.WithLogLevels(slog.AllLevels), ) if err != nil { return nil, fmt.Errorf("rotate handler: %w", err) } defer func() { if err != nil { _ = rotateH.Close() } }() // Add handlers logger.AddHandlers( handler.NewConsoleHandler(slog.AllLevels), errorH, rotateH, ) return logger, nil } func main() { logger, err := setupLogger() if err != nil { log.Fatalf("setup logger: %v", err) } defer func() { if err := logger.Close(); err != nil { fmt.Fprintf(os.Stderr, "close logger: %v\n", err) } }() // Use logger logger.Info("application started") // Safe error logging operationErr := errors.New("operation failed") if operationErr != nil { logger.ErrorT(operationErr) } // Ensure flush before exit if err := logger.Flush(); err != nil { fmt.Fprintf(os.Stderr, "flush error: %v\n", err) } } ``` -------------------------------- ### Simple Console Logging Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md Example demonstrating how to set up and use the logger for simple console output. ```APIDOC ## Simple Console Logging ```go logger := slog.NewStdLogger() logger.Info("application started") logger.Debugf("value: %d", 42) defer logger.Close() ``` ``` -------------------------------- ### Complete SubLogger Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sublogger.md A comprehensive example showing how to initialize a SubLogger with context, shared fields, and extra data, then use it to log within a processing loop. ```go package main import ( "context" "github.com/gookit/slog" "github.com/gookit/slog/handler" ) func processItems(ctx context.Context, items []string) { // Create SubLogger with shared context and fields sl := slog.NewSub(). KeepCtx(ctx). KeepFields(slog.M{ "batch": "items-2024-01", "processor": "main", }). KeepExtra(slog.M{ "start_time": getTime(), }) defer sl.Release() sl.Info("processing started") for idx, item := range items { // Add per-iteration data sl.WithData(slog.M{ "index": idx, "item": item, "total": len(items), }).Info("processing item") if err := processItem(item); err != nil { sl.ErrorT(err) continue } } sl.Info("processing completed") } func main() { logger := slog.New() logger.AddHandler(handler.NewConsoleHandler(slog.AllLevels)) defer logger.Close() ctx := context.Background() processItems(ctx, []string{"a", "b", "c"}) } ``` -------------------------------- ### Full JSON Formatter Configuration Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/formatter.md This example demonstrates a comprehensive configuration of the JSONFormatter, including setting specific fields, enabling pretty-printing, defining a custom time format, and applying field aliases. It also shows how to integrate the formatter with a console handler. ```go formatter := slog.NewJSONFormatter(func(f *JSONFormatter) { f.Fields = []string{ slog.FieldKeyDatetime, slog.FieldKeyLevel, slog.FieldKeyMessage, slog.FieldKeyData, } f.PrettyPrint = true f.TimeFormat = "2006-01-02 15:04:05" f.Aliases = slog.StringMap{ "message": "msg", "level": "severity", } }) handler := handler.NewConsoleHandler(slog.AllLevels) handler.SetFormatter(formatter) ``` -------------------------------- ### Simple Text Formatter Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/formatter.md Demonstrates basic usage of the TextFormatter with a custom template for console output. ```go package main import ( "github.com/gookit/slog" "github.com/gookit/slog/handler" ) func main() { h := handler.NewConsoleHandler(slog.AllLevels) // Simple format f := slog.NewTextFormatter("[{{level}}] {{message}}\n") h.SetFormatter(f) logger := slog.NewWithHandlers(h) logger.Info("simple message") // Output: [INFO] simple message } ``` -------------------------------- ### Multiple Output Destinations Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md Example showing how to configure loggers for multiple output destinations, such as console and file. ```APIDOC ## Multiple Output Destinations ```go // Console logger consoleLogger := slog.NewStdLogger() // File logger fileLogger := slog.NewSugaredLogger( createFileWriter("/var/log/app.log"), slog.InfoLevel, ) consoleLogger.Info("to console and file") fileLogger.Info("to file only") defer consoleLogger.Close() defer fileLogger.Close() ``` ``` -------------------------------- ### Processor Execution Order Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/processor.md Demonstrates how processors execute in the order they are added to the logger, before handlers process the record. This example adds hostname, a unique request ID, and a custom service field. ```go logger := slog.New() // Processor 1: Add hostname logger.AddProcessor(slog.AddHostname()) // Processor 2: Add request ID logger.AddProcessor(slog.AddUniqueID("req_id")) // Processor 3: Custom processor logger.AddProcessor(slog.ProcessorFunc(func(r *slog.Record) { r.AddField("service", "api") })) // When logging, processors execute in order: // hostname -> req_id -> service logger.Info("message") ``` -------------------------------- ### Custom Configuration Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md Example demonstrating advanced custom configuration, including setting log level, disabling caller reporting, and customizing formatter settings like time format and color. ```APIDOC ## Custom Configuration ```go logger := slog.NewStdLogger(func(sl *slog.SugaredLogger) { sl.Level = slog.InfoLevel sl.ReportCaller = false // Customize formatter f := slog.AsTextFormatter(sl.Formatter) f.TimeFormat = "2006-01-02 15:04:05" f.EnableColor = true }) logger.Info("configured logger") defer logger.Close() ``` ``` -------------------------------- ### Basic Logger Setup and Usage Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/logger.md Demonstrates how to create a logger, add a console handler, include a hostname processor, and log messages with and without additional data. Ensure to defer logger cleanup. ```go package main import ( "github.com/gookit/slog" "github.com/gookit/slog/handler" ) func main() { // Create logger logger := slog.New() // Add handlers consoleHandler := handler.NewConsoleHandler(slog.AllLevels) logger.AddHandler(consoleHandler) // Add processor logger.AddProcessor(slog.AddHostname()) // Log messages logger.Info("application started") logger.WithData(slog.M{ "user": "john", "action": "login", }).Info("user logged in") // Cleanup defer logger.Close() } ``` -------------------------------- ### JSON Output Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md Example showing how to configure the logger for JSON output to a specified writer and log level. ```APIDOC ## JSON Output ```go logger := slog.NewJSONSugared(os.Stdout, slog.InfoLevel) logger.Info("message") defer logger.Close() ``` ``` -------------------------------- ### Simple Console Logging Setup Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md Sets up a basic logger that outputs to the console. Use `Info` for standard messages and `Debugf` for detailed debugging information. Ensure `Close()` is deferred for proper shutdown. ```go logger := slog.NewStdLogger() logger.Info("application started") logger.Debugf("value: %d", 42) defer logger.Close() ``` -------------------------------- ### JSONFormatter Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/formatter.md Provides a comprehensive example of how to instantiate and configure a JSONFormatter for structured logging, including setting fields, pretty-printing, time format, and aliases. ```APIDOC ## Example Usage ```go formatter := slog.NewJSONFormatter(func(f *JSONFormatter) { f.Fields = []string{ slog.FieldKeyDatetime, slog.FieldKeyLevel, slog.FieldKeyMessage, slog.FieldKeyData, } f.PrettyPrint = true f.TimeFormat = "2006-01-02 15:04:05" f.Aliases = slog.StringMap{ "message": "msg", "level": "severity", } }) handler := handler.NewConsoleHandler(slog.AllLevels) handler.SetFormatter(formatter) ``` ``` -------------------------------- ### SimpleFileHandler Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/handler.md Creates a simple file handler for a specified file path and maximum log level. The handler is then added to the logger. ```go h, err := handler.NewSimpleFileHandler("/tmp/error.log", slog.ErrorLevel) logger.AddHandler(h) ``` -------------------------------- ### Processor with Hostname Example and Output Source: https://github.com/gookit/slog/blob/master/README.md Shows how to add the `slog.AddHostname` processor and log a message. The output includes the added 'hostname' field. ```go slog.AddProcessor(slog.AddHostname()) slog.Info("message") ``` ```json {"channel":"application","level":"INFO","datetime":"2020/07/17 12:01:35","hostname":"InhereMac","data":{},"extra":{},"message":"message"} ``` -------------------------------- ### Adding Handlers Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md Example demonstrating how to add handlers to the logger, including using the SugaredLogger itself as a handler. ```APIDOC ## Adding Handlers ```go logger := slog.NewStdLogger() // SugaredLogger can also act as a handler slog.AddHandler(logger) // Create a separate logger mainLogger := slog.New() mainLogger.AddHandlers(logger) mainLogger.Info("via main logger") mainLogger.Warn("warning message") defer logger.Close() ``` ``` -------------------------------- ### LevelMode String Method Example Source: https://github.com/gookit/slog/blob/master/_autodocs/types.md Demonstrates the String() method for LevelMode, which returns the string representation of the mode. ```go slog.LevelModeList.String() // "list" slog.LevelModeMax.String() // "max" ``` -------------------------------- ### Custom Formatter Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md Example illustrating how to customize the text formatter's template and color settings. ```APIDOC ## Custom Formatter ```go logger := slog.NewStdLogger() // Customize text formatter f := slog.AsTextFormatter(logger.Formatter) f.SetTemplate("[{{level}}] {{message}}\n") f.EnableColor = false logger.Info("message") ``` ``` -------------------------------- ### JSON Logs to File Setup Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/handler.md Configure a file handler to output logs in JSON format with a specified buffer size. Ensure to handle potential errors during handler creation. ```go h, err := handler.NewFileHandler( "/var/log/app.json", handler.WithUseJSON(true), handler.WithBuffSize(8192), ) if err != nil { panic(err) } logger.AddHandler(h) ``` -------------------------------- ### Multiple Output Destinations Setup Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md Configures logging to multiple destinations simultaneously: one logger for the console and another for a file. Each logger should have its `Close()` method deferred. ```go // Console logger consoleLogger := slog.NewStdLogger() // File logger fileLogger := slog.NewSugaredLogger( createFileWriter("/var/log/app.log"), slog.InfoLevel, ) consoleLogger.Info("to console and file") fileLogger.Info("to file only") defer consoleLogger.Close() defer fileLogger.Close() ``` -------------------------------- ### Start Flush Daemon Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/logger.md Starts a background goroutine that periodically flushes logs. Callbacks can be provided to execute when the daemon stops. ```go logger.FlushDaemon( func() { log.Println("daemon stopped") }, ) ``` -------------------------------- ### Rotating Log Files Setup Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/handler.md Set up a handler that automatically rotates log files daily, compresses them, and keeps a specified number of backup files. Ensure to close the logger when done. ```go logger := slog.New() h, err := handler.NewRotateFileHandler( "/var/log/app.log", rotatefile.EveryDay, handler.WithCompress(true), handler.WithBackupNum(7), // Keep 7 days ) if err != nil { panic(err) } logger.AddHandler(h) defer logger.Close() // Important for flushing ``` -------------------------------- ### Custom Processor Implementation Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/processor.md Provides an example of how to implement a custom processor by defining a struct and its `Process` method, and how to add it to the logger. ```APIDOC ## Processor Interface Implementation Complete custom processor implementation: ```go type CustomProcessor struct { ServiceName string } func (p *CustomProcessor) Process(r *slog.Record) { // Modify the record r.AddField("service", p.ServiceName) // Add context values if available if r.Ctx != nil { if userID := r.Ctx.Value("user_id"); userID != nil { r.AddField("user_id", userID) } } // Add calculated data r.SetExtraValue("memory_mb", getMemoryMB()) } // Usage logger := slog.New() logger.AddProcessor(&CustomProcessor{ ServiceName: "payment-service", }) ``` ``` -------------------------------- ### Set Formatter Source: https://github.com/gookit/slog/blob/master/_autodocs/configuration.md Sets the formatter for the default logger. This example shows how to set a JSON formatter. ```Go slog.SetFormatter(slog.NewJSONFormatter()) ``` -------------------------------- ### Initialize Logger and Add Console Handler Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/record.md Sets up a new slog logger and attaches a console handler that processes all log levels. This is a common setup for basic logging. ```go package main import ( "github.com/gookit/slog" "github.com/gookit/slog/handler" ) func main() { logger := slog.New() logger.AddHandler(handler.NewConsoleHandler(slog.AllLevels)) // ... rest of the code ... defer logger.Close() } ``` -------------------------------- ### Multiple Handlers Configuration Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/handler.md This example shows how to add multiple handlers to a single logger instance: a console handler for all levels, a file handler for errors, and a rotating file handler for informational messages. ```go logger := slog.New() // Console for all levels console := handler.NewConsoleHandler(slog.AllLevels) logger.AddHandler(console) // File for errors only errFile, _ := handler.NewFileHandler( "/var/log/errors.log", handler.WithLogLevels(slog.DangerLevels), ) logger.AddHandler(errFile) // Rotating file for info infoFile, _ := handler.NewRotateFileHandler( "/var/log/info.log", rotatefile.EveryHour, handler.WithLogLevels(slog.NormalLevels), ) logger.AddHandler(infoFile) defer logger.Close() ``` -------------------------------- ### Nested SubLoggers Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sublogger.md Demonstrates creating nested SubLoggers, where an inner SubLogger inherits context from an outer one. Both outer and inner operations are logged with their respective fields. Ensure defer sl.Release() is used for each SubLogger. ```go func outerOperation(ctx context.Context) { // Outer SubLogger outerSl := slog.NewSub(). KeepCtx(ctx). KeepFields(slog.M{"level": "outer"}) defer outerSl.Release() outerSl.Info("outer operation started") // Create nested SubLogger with parent's context innerSl := slog.NewSub(). KeepCtx(ctx). KeepFields(slog.M{ "level": "inner", "parent": "outer", }) defer innerSl.Release() innerSl.Info("inner operation started") innerSl.Info("inner operation finished") outerSl.Info("outer operation finished") } ``` -------------------------------- ### Configure Handler with Maximum Log Level Source: https://github.com/gookit/slog/blob/master/_autodocs/configuration.md Use `WithLogLevel` to set a maximum severity level. This example includes info level and all higher severity levels. ```go config := handler.NewConfig( handler.WithLogfile("/var/log/app.log"), handler.WithLogLevel(slog.InfoLevel), // Info and all higher severity ) ``` -------------------------------- ### TextFormatter Custom Template Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/formatter.md Demonstrates creating a TextFormatter with a custom template that includes user-defined fields like 'user_id' and 'request_id'. ```go formatter := slog.NewTextFormatter( "[{{datetime}}] [{{level}}] {{message}} | User: {{user_id}} | RequestID: {{request_id}}\n", ) ``` -------------------------------- ### JSON Output Logger Setup Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md Configures a logger to output messages in JSON format to a specified writer and log level. Remember to defer `Close()` for cleanup. ```go logger := slog.NewJSONSugared(os.Stdout, slog.InfoLevel) logger.Info("message") defer logger.Close() ``` -------------------------------- ### Custom Text Formatter Setup Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md Initializes a standard logger and then customizes its text formatter by setting a specific template and disabling color output. The `SetTemplate` method allows defining the log message structure. ```go logger := slog.NewStdLogger() // Customize text formatter f := slog.AsTextFormatter(logger.Formatter) f.SetTemplate("[{{level}}] {{message}}\n") f.EnableColor = false logger.Info("message") ``` -------------------------------- ### CtxKeysProcessor Usage Examples Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/processor.md Demonstrates using CtxKeysProcessor to extract context values and place them into 'data', 'fields', or 'extra' destinations within the log record. Requires context to be attached to the logger. ```go ctx := context.WithValue( context.Background(), "user_id", 456, ) logger := slog.New() // Put in Fields logger.AddProcessor(slog.CtxKeysProcessor("fields", "user_id")) // Or in Data logger.AddProcessor(slog.CtxKeysProcessor("data", "user_id")) // Or in Extra logger.AddProcessor(slog.CtxKeysProcessor("extra", "user_id")) logger.WithContext(ctx).Info("message") ``` -------------------------------- ### Configure Handler with Specific Log Levels Source: https://github.com/gookit/slog/blob/master/_autodocs/configuration.md Use `WithLogLevels` to filter logs by a specific list of levels. This example includes only error, warn, fatal, and panic levels. ```go config := handler.NewConfig( handler.WithLogfile("/var/log/app.log"), handler.WithLogLevels(slog.DangerLevels), // Only error, warn, fatal, panic ) ``` -------------------------------- ### AppendCtxKeys Processor Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/processor.md Extracts values from the log record's context using specified keys and adds them as fields to the log record. Requires context to be attached to the logger. ```go ctx := context.WithValue( context.Background(), "user_id", 123, ) cxt = context.WithValue(ctx, "request_id", "abc-123") logger := slog.New() logger.AddProcessor(slog.AppendCtxKeys("user_id", "request_id")) logger.WithContext(ctx).Info("user action") // Fields include user_id and request_id from context ``` -------------------------------- ### MemoryUsage Processor Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/processor.md Adds current memory usage statistics (from runtime.MemStats) to the log record's Extra fields. Useful for monitoring application performance. ```go logger := slog.New() logger.AddProcessor(slog.MemoryUsage) logger.Info("checkpoint") // Logs include current memory usage ``` -------------------------------- ### Configure and Use File Handlers Source: https://github.com/gookit/slog/blob/master/README.md Demonstrates setting up two file handlers with different log levels and custom text formatting. Ensure logger.Close() is called if buffering is enabled. ```go package mypkg import ( "github.com/gookit/slog" "github.com/gookit/slog/handler" ) func main() { defer slog.MustClose() // DangerLevels contains: slog.PanicLevel, slog.ErrorLevel, slog.WarnLevel h1 := handler.MustFileHandler("/tmp/error.log", handler.WithLogLevels(slog.DangerLevels)) // custom log format // f := h1.Formatter().(*slog.TextFormatter) f := slog.AsTextFormatter(h1.Formatter()) f.SetTemplate("your template format\n") // NormalLevels contains: slog.InfoLevel, slog.NoticeLevel, slog.DebugLevel, slog.TraceLevel h2 := handler.MustFileHandler("/tmp/info.log", handler.WithLogLevels(slog.NormalLevels)) // register handlers slog.PushHandler(h1) slog.PushHandler(h2) // add logs slog.Info("info message text") slog.Error("error message text") } ``` -------------------------------- ### Create Handler with Config Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/handler.md Demonstrates creating a handler configuration using the Config struct and then creating the handler from the configuration. Useful for setting multiple options at once. ```go c := handler.NewConfig( handler.WithLogfile("/tmp/app.log"), handler.WithLogLevels(slog.AllLevels), handler.WithBuffSize(8192), ) h, err := c.CreateHandler() ``` -------------------------------- ### Configure Multiple Handlers Source: https://github.com/gookit/slog/blob/master/_autodocs/GUIDE.md Demonstrates setting up a logger with multiple handlers: a console handler for all logs, a file handler for errors, and a rotating file handler for all logs. ```go logger := slog.New() // Console for all logger.AddHandler(handler.NewConsoleHandler(slog.AllLevels)) // File for errors only errorFile, _ := handler.NewFileHandler( "/var/log/errors.log", handler.WithLogLevels(slog.DangerLevels), ) logger.AddHandler(errorFile) // Rotating file for everything allFile, _ := handler.NewRotateFileHandler( "/var/log/app.log", rotatefile.EveryDay, ) logger.AddHandler(allFile) defer logger.Close() ``` -------------------------------- ### Create Basic Logger Source: https://github.com/gookit/slog/blob/master/_autodocs/GUIDE.md Instantiate a basic logger and add a console handler for all log levels. Remember to close the logger when done. ```go logger := slog.New() logger.AddHandler(handler.NewConsoleHandler(slog.AllLevels)) logger.Info("custom logger") defer logger.Close() ``` -------------------------------- ### Template Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/formatter.md Gets the current template string of the TextFormatter. ```APIDOC ## Template ### Description Gets the current template string of the TextFormatter. ### Method `Template() string` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Request Example ```go template := formatter.Template() ``` ### Response #### Success Response (200) * Returns: The template string. #### Response Example * None ``` -------------------------------- ### Using the Global SugaredLogger Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md Shows how to use the globally available SugaredLogger for quick logging. It also illustrates how to configure this global logger's level and retrieve its instance. ```go // These use the global SugaredLogger slog.Info("message") slog.Warn("warning") // Configure it slog.Configure(func(sl *slog.SugaredLogger) { sl.Level = slog.DebugLevel }) // Get the standard logger stdLogger := slog.Std() ``` -------------------------------- ### Get Logger Name Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/logger.md Retrieves the currently set name of the logger. ```go name := logger.Name() ``` -------------------------------- ### Basic Logging with Slog Source: https://github.com/gookit/slog/blob/master/README.md Demonstrates basic logging of INFO, WARN, INFOF, and DEBUGF messages using the default logger. ```go package main import ( "github.com/gookit/slog" ) func main() { slog.Info("info log message") slog.Warn("warning log message") slog.Infof("info log %s", "message") slog.Debugf("debug %s", "message") } ``` -------------------------------- ### Name Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/logger.md Gets the logger name. Retrieves the currently set name for the logger instance. ```APIDOC ## Name() ### Description Gets the logger name. ### Method Signature `Name() string` ### Returns - **string** - The logger name. ### Request Example ```go name := logger.Name() ``` ``` -------------------------------- ### Configure File Handler Source: https://github.com/gookit/slog/blob/master/_autodocs/configuration.md Set up a file handler with a specified log file path, buffer size, and log levels. ```go h, err := handler.NewFileHandler("/var/log/app.log", handler.WithBuffSize(8192), handler.WithLogLevels(slog.AllLevels), ) ``` -------------------------------- ### Run Benchmarks Source: https://github.com/gookit/slog/blob/master/README.md Initiate benchmark tests using the make test-bench command. ```bash make test-bench ``` -------------------------------- ### Get Exit Handlers Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/logger.md Retrieves all currently registered exit handler functions. This can be used for inspection or debugging. ```go handlers := logger.ExitHandlers() ``` -------------------------------- ### Get TextFormatter Template Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/formatter.md Retrieves the current output template string from the TextFormatter. Use this to inspect the current format. ```go template := formatter.Template() ``` -------------------------------- ### Configuring File Logging Source: https://github.com/gookit/slog/blob/master/_autodocs/00-START-HERE.md Set up logging to a file by creating a file handler and adding it to the logger. Ensure the logger is closed afterwards. ```go h, _ := handler.NewFileHandler("/var/log/app.log") logger.AddHandler(h) defer logger.Close() ``` -------------------------------- ### Formattable Interface Definition Source: https://github.com/gookit/slog/blob/master/_autodocs/types.md Defines an interface for objects that can get and set a formatter. This is used by handlers to customize log output. ```go type Formattable interface { Formatter() Formatter SetFormatter(Formatter) } ``` -------------------------------- ### Create Logger with Handlers Source: https://github.com/gookit/slog/blob/master/_autodocs/GUIDE.md Initialize a logger and immediately configure it with specific handlers, such as a console handler. ```go logger := slog.NewWithHandlers( handler.NewConsoleHandler(slog.AllLevels), ) logger.Info("configured logger") ``` -------------------------------- ### Basic Logging Methods Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sugared-logger.md Utilize standard logging methods for different severity levels. These methods accept a variable number of arguments. ```go logger.Trace(args...) logger.Debug(args...) logger.Info(args...) logger.Notice(args...) logger.Warn(args...) logger.Error(args...) logger.Fatal(args...) logger.Panic(args...) ``` -------------------------------- ### AddUniqueID Processor Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/processor.md Generates a unique MD5-based ID for each log record and adds it as a specified field. Useful for tracing requests. ```go logger := slog.New() logger.AddProcessor(slog.AddUniqueID("request_id")) logger.Info("processing request") // Logs include unique "request_id" field ``` -------------------------------- ### Creating and Configuring a Custom Logger Source: https://github.com/gookit/slog/blob/master/_autodocs/00-START-HERE.md Instantiate a new logger, add a console handler with all log levels, and log a message. Remember to close the logger when done. ```go logger := slog.New() h := handler.NewConsoleHandler(slog.AllLevels) logger.AddHandler(h) logger.Info("message") defer logger.Close() ``` -------------------------------- ### Configure Logger via Constructor, Config Function, and Builder Source: https://github.com/gookit/slog/blob/master/_autodocs/README.md Demonstrates three ways to configure a logger: directly via the constructor, using a configuration function, and employing a handler builder. ```go // Via constructor logger := slog.NewWithName("myapp") ``` ```go // Via config function logger.Config(func(l *slog.Logger) { l.ReportCaller = true }) ``` ```go // Via builder h := handler.NewBuilder(). WithLogfile("/var/log/app.log"). WithBuffSize(8192). Build() ``` -------------------------------- ### Get Formatted Timestamp Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/record.md Returns the string representation of the record's timestamp. The exact format depends on the logger's configuration. ```go ts := record.timestamp() // returns string representation ``` -------------------------------- ### Set Custom Formatter Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/handler.md Handlers can be configured with a custom formatter. This example sets a text formatter with color enabled before adding the handler to the logger. ```go h := handler.NewConsoleHandler(slog.AllLevels) f := slog.NewTextFormatter() f.EnableColor = true h.SetFormatter(f) logger.AddHandler(h) ``` -------------------------------- ### Configure Console Handler and Formatter Source: https://github.com/gookit/slog/blob/master/_autodocs/configuration.md Initialize a console handler and customize its formatter, including enabling color output. ```go h := handler.NewConsoleHandler(slog.AllLevels) // Customize formatter f := slog.NewTextFormatter() f.EnableColor = true h.SetFormatter(f) ``` -------------------------------- ### AddHostname Processor Example Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/processor.md Adds the system's hostname to each log record's fields. Useful for identifying the source machine in logs. ```go logger := slog.New() logger.AddProcessor(slog.AddHostname()) logger.AddHandler(handler.NewConsoleHandler(slog.AllLevels)) logger.Info("message") // Logs include hostname field ``` -------------------------------- ### Get Level Name String in Go Source: https://github.com/gookit/slog/blob/master/_autodocs/types.md Retrieves the string representation of a log level, such as 'INFO'. Useful for displaying or logging the level name. ```go name := slog.InfoLevel.String() // "INFO" ``` -------------------------------- ### Run Unit Tests Source: https://github.com/gookit/slog/blob/master/README.md Execute all unit tests for the project using the go test command. ```bash go test ./... ``` -------------------------------- ### Get Record Level Name Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/record.md Retrieves the string representation of the log level set for a record. Ensure the Level field is populated before calling. ```go record.Level = slog.InfoLevel name := record.LevelName() // "INFO" ``` -------------------------------- ### Get Level Name Alias in Go Source: https://github.com/gookit/slog/blob/master/_autodocs/types.md Provides an alias for the String() method, returning the string representation of a log level. Functionally identical to String(). ```go name := slog.InfoLevel.Name() // "INFO" ``` -------------------------------- ### Create Logger with File Output Source: https://github.com/gookit/slog/blob/master/_autodocs/README.md Initialize a new logger and add a file handler to direct logs to a specified file. Remember to close the logger when done to flush any buffered logs. ```go logger := slog.New() h, err := handler.NewFileHandler("/var/log/app.log") logger.AddHandler(h) defer logger.Close() ``` -------------------------------- ### Implement Custom Slog Handler Source: https://github.com/gookit/slog/blob/master/README.md Define a custom handler by implementing the slog.Handler interface. This example shows how to structure a handler that can write logs to a specified output. ```go type MyHandler struct { handler.LevelsWithFormatter Output io.Writer } func (h *MyHandler) Handle(r *slog.Record) error { // you can write log message to file or send to remote. } func (h *MyHandler) Flush() error {} func (h *MyHandler) Close() error {} ``` -------------------------------- ### Add Processor to Logger Example Source: https://github.com/gookit/slog/blob/master/README.md Demonstrates how to add a built-in processor like `slog.AddHostname` to a logger instance. This processor adds a 'hostname' field to each log record. ```go slog.AddProcessor(slog.AddHostname()) // or l := slog.New() l.AddProcessor(slog.AddHostname()) ``` -------------------------------- ### Processor Order and Dependencies Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/processor.md Demonstrates the order in which processors are added and how they can depend on each other. Processors are executed in the order they are added. ```APIDOC ## Processor Order and Dependencies Design processors to handle dependencies: ```go logger := slog.New() // 1. First, add base identifiers logger.AddProcessor(slog.AddUniqueID("request_id")) // 2. Then, add context values logger.AddProcessor(slog.AddHostname()) // 3. Finally, add calculated/derived values logger.AddProcessor(slog.ProcessorFunc(func(r *slog.Record) { // Can now safely reference fields added by previous processors r.AddField("timestamp", time.Now()) })) ``` ``` -------------------------------- ### Creating Records with Data Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/record.md Demonstrates different ways to create a record object and associate initial data or fields with it before logging. ```APIDOC ## Working with Records ### Creating Records with Data ```go logger := slog.New() // Using WithData record := logger.WithData(slog.M{ "action": "login", "user_id": 123, }) record.Info("user logged in") // Using WithFields record := logger.WithFields(slog.M{ "service": "auth", "region": "us-east", }) record.Info("authentication service started") // Using WithExtra record := logger.WithExtra(slog.M{ "latency_ms": 45, "cache": true, }) record.Info("operation completed") ``` ``` -------------------------------- ### Configure TextFormatter Template Source: https://github.com/gookit/slog/blob/master/_autodocs/configuration.md Set a custom template for the TextFormatter to control the log message structure. This example uses a simple template for datetime, level, and message. ```go formatter := slog.NewTextFormatter() formatter.SetTemplate("[{{datetime}}] [{{level}}] {{message}}\n") ``` -------------------------------- ### Implement Formatter Interface with FormatterFunc Source: https://github.com/gookit/slog/blob/master/_autodocs/types.md Shows how to create a FormatterFunc that formats a record's message. ```go fmt := slog.FormatterFunc(func(r *slog.Record) ([]byte, error) { return []byte(r.Message + "\n"), nil }) ``` -------------------------------- ### Handle Handler Flush/Close Errors in slog Source: https://github.com/gookit/slog/blob/master/_autodocs/errors.md Errors can occur during the flush or close operations of slog handlers. This example demonstrates how to check for and log these I/O errors. ```go err := handler.Flush() if err != nil { log.Printf("flush error: %v", err) } err := handler.Close() if err != nil { log.Printf("close error: %v", err) } ``` -------------------------------- ### Run Benchmark Tests (beta 2022.04.17) Source: https://github.com/gookit/slog/blob/master/_example/bench_loglibs.md Execute benchmark tests for logging libraries using go test. This command runs performance tests and records results for various logging implementations, specifying CPU, run flags, and benchmark parameters. ```shell $ go test -v -cpu=4 -run=none -bench=. -benchtime=10s -benchmem bench_loglibs_test.go goos: darwin goarch: amd64 cpu: Intel(R) Core(TM) i7-3740QM CPU @ 2.70GHz BenchmarkZapNegative BenchmarkZapNegative-4 130808992 91.91 ns/op 192 B/op 1 allocs/op BenchmarkZeroLogNegative BenchmarkZeroLogNegative-4 914445844 13.19 ns/op 0 B/op 0 allocs/op BenchmarkPhusLogNegative BenchmarkPhusLogNegative-4 792539167 15.32 ns/op 0 B/op 0 allocs/op BenchmarkLogrusNegative BenchmarkLogrusNegative-4 289393606 40.61 ns/op 16 B/op 1 allocs/op BenchmarkGookitSlogNegative BenchmarkGookitSlogNegative-4 29522170 405.3 ns/op 125 B/op 4 allocs/op BenchmarkZapPositive BenchmarkZapPositive-4 9113048 1283 ns/op 192 B/op 1 allocs/op BenchmarkZeroLogPositive BenchmarkZeroLogPositive-4 14691699 797.0 ns/op 0 B/op 0 allocs/op BenchmarkPhusLogPositive BenchmarkPhusLogPositive-4 27634338 424.5 ns/op 0 B/op 0 allocs/op BenchmarkLogrusPositive BenchmarkLogrusPositive-4 2734669 4363 ns/op 608 B/op 17 allocs/op BenchmarkGookitSlogPositive BenchmarkGookitSlogPositive-4 7740348 1563 ns/op 165 B/op 6 allocs/op PASS ok command-line-arguments 145.175s ``` -------------------------------- ### Configure and Use TextFormatter in Handler Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/formatter.md Shows how to configure a TextFormatter with custom time format, color, and template, and then apply it to a console handler. ```go formatter := slog.NewTextFormatter() formatter.TimeFormat = "2006-01-02 15:04:05" formatter.EnableColor = true formatter.SetTemplate("{{datetime}} [{{level}}] {{message}}\n") // Use in handler handler := handler.NewConsoleHandler(slog.AllLevels) handler.SetFormatter(formatter) logger.AddHandler(handler) ``` -------------------------------- ### Implement Processor Interface with ProcessorFunc Source: https://github.com/gookit/slog/blob/master/_autodocs/types.md Demonstrates creating a ProcessorFunc to add a field to a record. ```go proc := slog.ProcessorFunc(func(r *slog.Record) { r.AddField("service", "api") }) ``` -------------------------------- ### Get Lowercase Level Name in Go Source: https://github.com/gookit/slog/blob/master/_autodocs/types.md Returns the lowercase string representation of a log level, such as 'info'. Useful for case-insensitive comparisons or specific output formats. ```go name := slog.InfoLevel.LowerName() // "info" ``` -------------------------------- ### Configure and Use Rotate File Handlers Source: https://github.com/gookit/slog/blob/master/README.md Sets up two rotating file handlers, one for danger levels and one for normal levels, both rotating hourly. Logs are then added to the logger. ```go func Example_rotateFileHandler() { h1 := handler.MustRotateFile("/tmp/error.log", handler.EveryHour, handler.WithLogLevels(slog.DangerLevels)) h2 := handler.MustRotateFile("/tmp/info.log", handler.EveryHour, handler.WithLogLevels(slog.NormalLevels)) slog.PushHandler(h1) slog.PushHandler(h2) // add logs slog.Info("info message") slog.Error("error message") } ``` -------------------------------- ### Create Slog Configuration Source: https://github.com/gookit/slog/blob/master/handler/README.md Instantiate a new configuration using `NewConfig` or `NewEmptyConfig`, optionally providing configuration functions. ```go type Config struct{ ... } func NewConfig(fns ...ConfigFn) *Config func NewEmptyConfig(fns ...ConfigFn) *Config ``` -------------------------------- ### Create Handler Config via Constructor Source: https://github.com/gookit/slog/blob/master/_autodocs/configuration.md Instantiate handler configuration with multiple options using a constructor. Suitable for setting up a logger with predefined settings. ```go config := handler.NewConfig( handler.WithLogfile("/var/log/app.log"), handler.WithBuffSize(8192), handler.WithLogLevels(slog.AllLevels), ) h, err := config.CreateHandler() ``` -------------------------------- ### Ensure Logger Cleanup on Exit Source: https://github.com/gookit/slog/blob/master/_autodocs/errors.md Always ensure that buffered logs are written before application exit by calling Close() or Flush(). This example demonstrates deferred cleanup to handle potential errors. ```go // Always ensure cleanup defer func() { if err := logger.Close(); err != nil { fmt.Fprintf(os.Stderr, "logger close error: %v\n", err) } }() ``` -------------------------------- ### Configure Email Handler and Level Limits Source: https://github.com/gookit/slog/blob/master/_autodocs/configuration.md Set up an email handler with SMTP details and recipient addresses. Optionally, limit the handler to only critical log levels. ```go emailHandler := handler.NewEmailHandler( handler.EmailOption{ SMTPHost: "smtp.gmail.com", SMTPPort: 587, FromAddr: "alerts@example.com", Password: "app-specific-password", }, []string{"ops@example.com", "admin@example.com"}, ) // Set to only handle critical levels h.SetLimitLevels([]slog.Level{ slog.PanicLevel, slog.FatalLevel, }) ``` -------------------------------- ### Run Benchmark Tests (v0.3.5) Source: https://github.com/gookit/slog/blob/master/_example/bench_loglibs.md Execute benchmark tests for logging libraries using make test-bench. This command runs performance tests and records results for various logging implementations. ```shell % make test-bench goos: darwin goarch: amd64 cpu: Intel(R) Core(TM) i7-3740QM CPU @ 2.70GHz BenchmarkZapNegative BenchmarkZapNegative-4 123297997 110.4 ns/op 192 B/op 1 allocs/op BenchmarkZeroLogNegative BenchmarkZeroLogNegative-4 891508806 13.36 ns/op 0 B/op 0 allocs/op BenchmarkPhusLogNegative BenchmarkPhusLogNegative-4 811990076 14.74 ns/op 0 B/op 0 allocs/op BenchmarkLogrusNegative BenchmarkLogrusNegative-4 242633541 49.40 ns/op 16 B/op 1 allocs/op BenchmarkGookitSlogNegative BenchmarkGookitSlogNegative-4 29102253 422.8 ns/op 125 B/op 4 allocs/op BenchmarkZapPositive BenchmarkZapPositive-4 9772791 1194 ns/op 192 B/op 1 allocs/op BenchmarkZeroLogPositive BenchmarkZeroLogPositive-4 13944360 856.8 ns/op 0 B/op 0 allocs/op BenchmarkPhusLogPositive BenchmarkPhusLogPositive-4 27839614 431.2 ns/op 0 B/op 0 allocs/op BenchmarkLogrusPositive BenchmarkLogrusPositive-4 2621076 4583 ns/op 608 B/op 17 allocs/op BenchmarkGookitSlogPositive BenchmarkGookitSlogPositive-4 8908768 1359 ns/op 149 B/op 5 allocs/op PASS ok command-line-arguments 149.379s ``` -------------------------------- ### Manually Create and Modify a Log Record Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/record.md Demonstrates how to manually create a new log record, set its level, message, and add data and fields. This provides fine-grained control over log record content. ```go record := logger.NewRecord() record.Level = slog.ErrorLevel record.Message = "database error" record.AddData(slog.M{ "error_code": 1234, "table": "users", }) record.AddField("severity", "high") // Use it... ``` -------------------------------- ### Create Simple Handler Source: https://github.com/gookit/slog/blob/master/README.md Instantiate a simple handler that writes logs to a given io.Writer. ```go // A simple handler implementation that outputs logs to a given io.Writer func NewSimpleHandler(out io.Writer, level slog.Level) *SimpleHandler ``` -------------------------------- ### Service Handler with Tracing and SubLogger Source: https://github.com/gookit/slog/blob/master/_autodocs/api-reference/sublogger.md Create a SubLogger with an existing logger, context, fields, and data for service request handling. Use defer sl.Release() for cleanup. Logs will include service, trace ID, customer ID, and amount. ```go func handleServiceRequest(logger *slog.Logger, ctx context.Context, req Request) Response { // Create SubLogger with request tracing sl := slog.NewSubWith(logger). KeepCtx(ctx). KeepFields(slog.M{ "service": "payment", "trace_id": req.TraceID, }). KeepData(slog.M{ "customer_id": req.CustomerID, "amount": req.Amount, }) defer sl.Release() sl.Info("request received") // Validate if err := validateRequest(req); err != nil { sl.Error("validation failed") return Response{Error: err} } sl.Info("validation passed") // Process result := processPayment(req) sl.WithExtra(slog.M{ "transaction_id": result.ID, "timestamp": result.Time, }).Info("payment processed") return result } ``` -------------------------------- ### Handling Standard Go Errors Source: https://github.com/gookit/slog/blob/master/_autodocs/errors.md When a slog handler encounters an error, it returns standard Go errors. This example shows how to check for specific errors like permission or not found issues from the 'os' package. ```go if err != nil { if os.IsPermission(err) { // Handle permission error } else if os.IsNotExist(err) { // Handle not found error } else { // Handle other file errors } } ```