2025-05-21 12:39:40 +07:00

119 lines
2.8 KiB
Markdown

# Logger Package
A structured, high-performance logging package built on top of Logrus with the following features:
## Features
- **Structured Logging**: JSON and Text formats supported
- **Level-based Logging**: Debug, Info, Warn, Error, Fatal, Panic, Trace
- **Performance Optimized**: Low allocation design with sync.Pool
- **Context Support**: Add request-scoped fields
- **Caller Information**: Automatically include file and line numbers
- **Multiple Outputs**: Stdout/Stderr separation
- **Thread-safe**: Safe for concurrent use
- **Customizable**: Various configuration options
## Installation
```go
import "starter-kit/internal/helper/logger"
```
## Basic Usage
### Initialization
```go
// Initialize with default configuration
logger.Init(&logger.LogConfig{
Level: "info",
Format: "json",
EnableCaller: true,
ReportCaller: true,
})
```
### Logging Messages
```go
// Simple logging
logger.Info("Application started")
logger.Debug("Debug information")
logger.Warn("Warning message")
logger.Error("Error occurred")
// With fields
logger.WithFields(logger.Fields{
"key": "value",
"num": 42,
}).Info("Log with fields")
// With error
if err != nil {
logger.WithError(err).Error("Operation failed")
}
```
## Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| Level | string | "info" | Log level (debug, info, warn, error, fatal, panic) |
| Format | string | "json" | Output format (json, text) |
| EnableCaller | bool | true | Include caller information |
| BufferSize | int | 256 | Buffer size for async logging |
| DisableColor | bool | false | Disable colored output (text format only) |
| ReportCaller | bool | true | Report the calling method |
## Best Practices
1. **Use Appropriate Log Levels**:
- ERROR: Something failed, needs attention
- WARN: Unexpected but handled situation
- INFO: Important business process has started/ended
- DEBUG: Detailed information for debugging
2. **Structured Logging**:
- Always use fields for structured data
- Keep log messages concise and consistent
3. **Performance**:
- Use `WithFields` when logging multiple key-value pairs
- Avoid expensive operations in log statements
## Example Output
### JSON Format
```json
{
"@timestamp": "2023-04-01T12:00:00Z",
"level": "info",
"message": "Request processed",
"caller": "handler/user.go:42",
"method": "GET",
"path": "/api/users",
"status": 200,
"duration": 42.5,
"request_id": "abc123"
}
```
### Text Format
```
INFO[0000] Request processed caller=handler/user.go:42 method=GET path=/api/users status=200 duration=42.5 request_id=abc123
```
## Testing
```bash
# Run tests
go test -v ./...
# Run with race detector
go test -race ./...
```
## License
[MIT](LICENSE)