Documentation
¶
Overview ¶
Package logutil provides utility functions for common logging tasks. It works with any logger that implements the log.Logger interface.
Example (HttpHandler) ¶
Example of using logutil in an HTTP handler
package main
import (
"context"
"net/http"
"net/http/httptest"
"time"
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
handler := func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// Log incoming request
logutil.LogHTTPRequest(logger, r)
// Add request ID to context and create request-scoped logger
ctx := context.WithValue(r.Context(), "request_id", "req-789")
requestLogger := logutil.WithRequestID(ctx, logger)
// Use timer to measure processing time
defer logutil.Timer(requestLogger, "request_processing")()
// Simulate request processing
err := processRequest(r)
if logutil.CheckError(requestLogger, err, "Failed to process request") {
http.Error(w, "Internal Server Error", 500)
logutil.LogHTTPResponse(logger, r, 500, time.Since(start))
return
}
w.WriteHeader(200)
w.Write([]byte("OK"))
// Log response
logutil.LogHTTPResponse(logger, r, 200, time.Since(start))
}
// Create test request
req := httptest.NewRequest("POST", "http://example.com/api/process", nil)
w := httptest.NewRecorder()
handler(w, req)
}
func processRequest(r *http.Request) error {
_ = r
return nil
}
Index ¶
- func CheckError(logger log.Logger, err error, msg string) bool
- func DebugIf(logger log.Logger, condition bool, msg string, args ...any)
- func ErrorIf(logger log.Logger, condition bool, msg string, args ...any)
- func FatalOnError(logger log.Logger, err error, msg string)
- func InfoIf(logger log.Logger, condition bool, msg string, args ...any)
- func LogError(logger log.Logger, err error, msg string)
- func LogHTTPRequest(logger log.Logger, req *http.Request)
- func LogHTTPResponse(logger log.Logger, req *http.Request, statusCode int, duration time.Duration)
- func LogPanic(logger log.Logger, operation string)
- func LogPanicAsError(logger log.Logger, operation string)
- func LogShutdown(logger log.Logger, appName string, uptime time.Duration)
- func LogStartup(logger log.Logger, appName, version string, port int)
- func Must(logger log.Logger, err error, msg string)
- func TimeFunction(logger log.Logger, name string, fn func())
- func Timer(logger log.Logger, name string) func()
- func WarnIf(logger log.Logger, condition bool, msg string, args ...any)
- func WithRequestID(ctx context.Context, logger log.Logger) log.Logger
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CheckError ¶
CheckError logs an error if it's not nil and returns whether an error occurred. This is useful for error checking in conditional statements.
Example ¶
package main
import (
"errors"
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
err := performOperation()
if logutil.CheckError(logger, err, "Operation failed") {
// Handle error case
return
}
// Continue with success case
}
func performOperation() error {
return errors.New("simulated error")
}
func DebugIf ¶
DebugIf logs a debug message only if the condition is true. This helps reduce conditional logging boilerplate in application code.
func ErrorIf ¶
ErrorIf logs an error message only if the condition is true. This helps reduce conditional logging boilerplate in application code.
Example ¶
package main
import (
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
hasError := true
logutil.ErrorIf(logger, hasError, "Validation failed", "field", "email")
// Only logs if hasError is true
}
func FatalOnError ¶
FatalOnError logs an error and exits the program if the error is not nil. This should be used sparingly, only for unrecoverable errors during startup.
func InfoIf ¶
InfoIf logs an info message only if the condition is true. This helps reduce conditional logging boilerplate in application code.
Example ¶
package main
import (
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
debugMode := true
logutil.InfoIf(logger, debugMode, "Debug mode is enabled", "config", "debug")
// Only logs if debugMode is true
}
func LogError ¶
LogError logs an error if it's not nil. This is a convenience function to avoid repetitive error checking in code.
Example ¶
package main
import (
"errors"
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
err := errors.New("database connection failed")
logutil.LogError(logger, err, "Failed to connect to database")
// Only logs if err is not nil
}
func LogHTTPRequest ¶
LogHTTPRequest logs details about an HTTP request. It records the HTTP method, URL, remote address, and user agent.
Example ¶
package main
import (
"net/http/httptest"
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
req := httptest.NewRequest("GET", "http://example.com/api/users", nil)
req.Header.Set("User-Agent", "MyApp/1.0")
logutil.LogHTTPRequest(logger, req)
// Output logs HTTP request details including method, URL, and user agent
}
func LogHTTPResponse ¶
LogHTTPResponse logs details about an HTTP response. It records the HTTP method, URL, status code, and response duration.
Example ¶
package main
import (
"net/http/httptest"
"time"
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
req := httptest.NewRequest("GET", "http://example.com/api/users", nil)
// Simulate processing time
duration := 150 * time.Millisecond
statusCode := 200
logutil.LogHTTPResponse(logger, req, statusCode, duration)
// Output logs HTTP response details including status code and duration
}
func LogPanic ¶
LogPanic recovers from a panic and logs it as an error. This should be used with defer in functions that might panic.
Example usage:
defer LogPanic(logger, "processing_request")
func LogPanicAsError ¶
LogPanicAsError recovers from a panic and logs it as an error without re-panicking. This is useful when you want to handle panics gracefully.
Example usage:
defer LogPanicAsError(logger, "background_task")
Example ¶
package main
import (
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
func() {
defer logutil.LogPanicAsError(logger, "background_task")
// This will panic but be caught and logged as an error
panic("unexpected error occurred")
}()
// Function continues execution after panic is caught and logged
}
func LogShutdown ¶
LogShutdown logs application shutdown information. This is a convenience function for logging shutdown details.
Example ¶
package main
import (
"time"
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
startTime := time.Now()
// Simulate application running
time.Sleep(100 * time.Millisecond)
uptime := time.Since(startTime)
logutil.LogShutdown(logger, "my-web-service", uptime)
// Logs application shutdown information including uptime
}
func LogStartup ¶
LogStartup logs application startup information. This is a convenience function for logging common startup details.
Example ¶
package main
import (
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
logutil.LogStartup(logger, "my-web-service", "v1.2.3", 8080)
// Logs application startup information including name, version, and port
}
func Must ¶
Must logs a fatal error and exits if err is not nil. This is similar to FatalOnError but with a shorter name for convenience.
func TimeFunction ¶
TimeFunction executes a function and logs its execution time. This is a convenience wrapper around Timer for simple function timing.
Example ¶
package main
import (
"time"
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
// Use TimeFunction to measure and log function execution time
logutil.TimeFunction(logger, "data_processing", func() {
// Simulate data processing
time.Sleep(100 * time.Millisecond)
})
// Automatically logs the execution time of the function
}
func Timer ¶
Timer returns a function that, when called, logs the elapsed time since Timer was called. This is useful for measuring and logging the duration of operations.
Example usage:
defer Timer(logger, "database_query")()
Example ¶
package main
import (
"time"
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
// Use Timer to measure operation duration
defer logutil.Timer(logger, "database_query")()
// Simulate database operation
time.Sleep(50 * time.Millisecond)
// When the function returns, it will log the operation duration
}
func WarnIf ¶
WarnIf logs a warning message only if the condition is true. This helps reduce conditional logging boilerplate in application code.
func WithRequestID ¶
WithRequestID extracts a request ID from context and returns a logger wrapper that automatically includes the request ID in all log messages. If no request ID is found in context, returns the original logger.
Example ¶
package main
import (
"context"
"github.com/kydenul/log"
"github.com/kydenul/log/logutil"
)
func main() {
logger := log.NewLog(nil)
// Create context with request ID
ctx := context.WithValue(context.Background(), "request_id", "req-123-456")
// Wrap logger to automatically include request ID
requestLogger := logutil.WithRequestID(ctx, logger)
// All log calls will now include the request ID
requestLogger.Info("Processing user request")
requestLogger.Error("Failed to process request")
}
Types ¶
This section is empty.