{"id":27963578,"url":"https://github.com/zakirkun/dy","last_synced_at":"2025-05-07T19:59:44.260Z","repository":{"id":283626525,"uuid":"952383133","full_name":"zakirkun/dy","owner":"zakirkun","description":"A powerful, flexible, and efficient logging package for Go applications with advanced context handling and error correlation.","archived":false,"fork":false,"pushed_at":"2025-03-28T14:18:58.000Z","size":38,"stargazers_count":7,"open_issues_count":0,"forks_count":5,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-07T19:59:39.879Z","etag":null,"topics":["error-handling","logging"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zakirkun.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-21T07:34:08.000Z","updated_at":"2025-04-11T02:22:43.000Z","dependencies_parsed_at":"2025-03-21T08:43:45.682Z","dependency_job_id":null,"html_url":"https://github.com/zakirkun/dy","commit_stats":null,"previous_names":["zakirkun/dy"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zakirkun%2Fdy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zakirkun%2Fdy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zakirkun%2Fdy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zakirkun%2Fdy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zakirkun","download_url":"https://codeload.github.com/zakirkun/dy/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252949271,"owners_count":21830151,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["error-handling","logging"],"created_at":"2025-05-07T19:59:43.666Z","updated_at":"2025-05-07T19:59:44.252Z","avatar_url":"https://github.com/zakirkun.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"./assets/logo.svg\" alt=\"dy Logo\" width=\"180\" height=\"180\"/\u003e\n  \u003ch1\u003edy\u003c/h1\u003e\n  \u003cp\u003eA powerful, flexible, and efficient logging package for Go applications with advanced context handling and error correlation.\u003c/p\u003e\n  \n  \u003cdiv\u003e\n    \u003ca href=\"https://pkg.go.dev/github.com/zakirkun/dy\"\u003e\u003cimg src=\"https://pkg.go.dev/badge/github.com/zakirkun/dy.svg\" alt=\"Go Reference\"\u003e\u003c/a\u003e\n    \u003ca href=\"LICENSE\"\u003e\u003cimg src=\"https://img.shields.io/badge/license-MIT-blue.svg\" alt=\"License\"\u003e\u003c/a\u003e\n    \u003c!-- \u003ca href=\"https://github.com/zakirkun/dy/actions\"\u003e\u003cimg src=\"https://github.com/zakirkun/dy/workflows/tests/badge.svg\" alt=\"Tests\"\u003e\u003c/a\u003e --\u003e\n    \u003ca href=\"https://goreportcard.com/report/github.com/zakirkun/dy\"\u003e\u003cimg src=\"https://goreportcard.com/badge/github.com/zakirkun/dy\" alt=\"Go Report Card\"\u003e\u003c/a\u003e\n  \u003c/div\u003e\n\u003c/div\u003e\n\n---\n\n## ✨ Features\n\n- 📊 **Multiple log levels**: DEBUG, INFO, WARN, ERROR, FATAL\n- 🎨 **Customizable output format** with timestamps and prefixes\n- 🔄 **Contextual logging** with inherited context chains\n- 🔍 **Advanced error correlation** for rich debugging information\n- 📌 **Function call tracing** with automatic indentation\n- 📝 **Structured logging** with JSON output format\n- 📂 **Caller information** (file, line, function)\n- 🌈 **Colored output** for terminal environments\n- 🔄 **Automatic log rotation** and backup management\n- 📦 **Compressed log archives**\n- 🔒 **Thread-safe operation**\n- ⚡ **Low overhead** with level-based filtering\n- 🌐 **Global default logger** and instance-based loggers\n\n## 📦 Installation\n\n```bash\ngo get github.com/zakirkun/dy\n```\n\n## 🚀 Basic Usage\n\n```go\npackage main\n\nimport (\n    \"github.com/zakirkun/dy\"\n)\n\nfunc main() {\n    // Use the default logger\n    dy.Info(\"This is an informational message\")\n    dy.Warn(\"This is a warning message\")\n    dy.Error(\"This is an error message: %s\", \"connection timeout\")\n    \n    // Create a custom logger\n    logger := dy.New(\n        dy.WithPrefix(\"APP\"),\n        dy.WithLevel(dy.DebugLevel),\n        dy.WithColor(true), // Enable colored output\n    )\n    \n    logger.Debug(\"Debug message with color\")\n    logger.Info(\"Custom logger info message\")\n}\n```\n\n## 🔄 Contextual Logging\n\nCreate child loggers that automatically inherit context from parent loggers:\n\n```go\n// Base application logger\nbaseLogger := dy.New(dy.WithLevel(dy.InfoLevel))\n\n// Create request-scoped logger with request ID\nreqLogger := baseLogger.WithContext(\"request_id\", \"abc-123\")\nreqLogger.Info(\"Request received\") // Logs with request_id=abc-123\n\n// Create user-scoped child logger that inherits request context\nuserLogger := reqLogger.WithContext(\"user_id\", \"user-456\") \nuserLogger.Info(\"User authenticated\") // Logs with request_id=abc-123 AND user_id=user-456\n\n// Add multiple fields at once\ntxLogger := userLogger.WithFields(map[string]interface{}{\n    \"transaction_id\": \"tx-789\",\n    \"amount\": 99.95,\n    \"currency\": \"USD\",\n})\ntxLogger.Info(\"Transaction started\") // Logs with ALL context values\n\n// Remove sensitive context for certain logs\nsanitizedLogger := txLogger.WithoutContext(\"user_id\")\nsanitizedLogger.Info(\"Metrics collected\") // Logs without the user_id\n```\n\n## 🔍 Error Correlation\n\nAutomatically capture detailed error information in your logs:\n\n```go\n// Basic error logging\nif err := db.Query(\"SELECT * FROM users\"); err != nil {\n    log.WithError(err).Error(\"Database query failed\")\n    // Automatically includes error message, type, and stack trace\n}\n\n// Add an error code\nlog.WithError(err).WithErrorCode(\"DB_CONN_FAILED\").Error(\"Database connection error\")\n\n// Create and wrap errors with rich context\nbaseErr := errors.New(\"network timeout\")\nwrappedErr := dy.WrapError(\n    baseErr,\n    \"API request failed\", \n    \"API_ERROR\",\n    map[string]interface{}{\n        \"endpoint\": \"/api/data\",\n        \"timeout_ms\": 500,\n    }\n)\nlog.WithError(wrappedErr).Error(\"External service unavailable\")\n```\n\nCustom error types can implement interfaces to provide additional context:\n\n```go\n// Define a custom error type with extra context\ntype DBError struct {\n    Err     error\n    Query   string\n    Params  []interface{}\n}\n\nfunc (e *DBError) Error() string {\n    return fmt.Sprintf(\"database error: %s\", e.Err)\n}\n\nfunc (e *DBError) Unwrap() error {\n    return e.Err\n}\n\n// Implement Fields() to add contextual information\nfunc (e *DBError) Fields() map[string]interface{} {\n    return map[string]interface{}{\n        \"query\":  e.Query,\n        \"params\": fmt.Sprintf(\"%v\", e.Params),\n    }\n}\n\n// Implement Code() for error code\nfunc (e *DBError) Code() string {\n    return \"DB_ERROR\"\n}\n\n// When logged, all this additional information is captured\nlog.WithError(\u0026DBError{\n    Err:    sql.ErrNoRows,\n    Query:  \"SELECT * FROM users WHERE id = ?\",\n    Params: []interface{}{123},\n}).Error(\"User not found\")\n```\n\n## 🔄 Log Rotation\n\n```go\npackage main\n\nimport (\n    \"time\"\n    \"github.com/zakirkun/dy\"\n)\n\nfunc main() {\n    // Create a logger with file rotation\n    logger := dy.New(\n        dy.WithRotateWriter(\"logs/application.log\", \n            dy.WithMaxSize(10),             // Rotate at 10MB\n            dy.WithMaxBackups(5),           // Keep 5 old logs\n            dy.WithBackupInterval(24*time.Hour), // Rotate daily\n            dy.WithCompress(true),          // Compress old logs\n        ),\n        dy.WithLevel(dy.InfoLevel),\n    )\n    // It's important to close the logger to flush any buffered data\n    defer logger.Close()\n    \n    logger.Info(\"Application started\")\n    \n    // Log will automatically rotate when:\n    // 1. File exceeds 10MB\n    // 2. 24 hours have passed since last rotation\n    // 3. Maximum 5 old log files will be kept\n}\n```\n\n## 🌈 Colored Output\n\nThe logger supports colored output in terminal environments:\n\n- 🔵 **DEBUG**: Blue\n- 🟢 **INFO**: Green\n- 🟡 **WARN**: Yellow\n- 🔴 **ERROR**: Red\n- 🟣 **FATAL**: Bold Red\n\nColors are automatically enabled by default when writing to a terminal (os.Stdout or os.Stderr) and can be toggled with the `WithColor` option.\n\n## 📌 Function Call Tracing\n\n```go\nfunc processData() {\n    // Log entry and exit of function with proper indentation\n    defer dy.TraceFunction()()\n    \n    dy.Info(\"Processing data...\")\n    // Do work here\n}\n```\n\n## 📝 JSON Output Format\n\n```go\nlogger := dy.New(\n    dy.WithJSONFormat(true),\n    dy.WithCallerInfo(true),\n)\n\nlogger.Info(\"This will be output in JSON format\")\n```\n\n## ⚙️ Configuration Options\n\n- `WithOutput(io.Writer)`: Set custom output destination\n- `WithLevel(Level)`: Set minimum log level \n- `WithPrefix(string)`: Add a prefix to all log messages\n- `WithTimestamp(bool)`: Enable/disable timestamps\n- `WithTrace(bool)`: Enable/disable function call tracing\n- `WithIndentString(string)`: Customize indentation for nested function calls\n- `WithJSONFormat(bool)`: Enable/disable JSON format\n- `WithCallerInfo(bool)`: Include caller file/line information\n- `WithColor(bool)`: Enable/disable colored output\n\n### 🔄 Context Options\n\n- `WithContext(key, value)`: Create a logger with an additional context field\n- `WithFields(map)`: Create a logger with multiple additional context fields\n- `WithoutContext(key)`: Create a logger without a specific context field\n- `WithError(err)`: Create a logger with rich error information\n- `WithErrorCode(code)`: Add or update an error code\n\n### 📦 Log Rotation Options\n\n- `WithRotateWriter(filename, options...)`: Use rotating file output\n  - `WithMaxSize(megabytes)`: Maximum file size before rotation\n  - `WithMaxBackups(count)`: Maximum number of old log files to retain\n  - `WithBackupInterval(duration)`: Time interval for regular rotation\n  - `WithCompress(bool)`: Enable/disable gzip compression of old logs\n\n## 🔍 Error Utilities\n\n- `NewError(message, code, fields)`: Create a rich error with code and context fields\n- `WrapError(err, message, code, fields)`: Wrap an existing error with additional context\n\n## ⚡ Performance\n\nThe package is designed to be efficient:\n\n- Minimal heap allocations\n- Level-based message filtering before string formatting\n- Concurrency-safe through mutex locking\n- Benchmark suite included\n\n## 📚 Examples\n\nSee the `example` folder for complete examples of usage.\n\n## 🔧 Compatibility\n\n- Requires Go 1.16 or later\n- No external dependencies\n\n## 📄 License\n\n[MIT License](LICENSE)\n\n## 👥 Contributing\n\nContributions are welcome! Feel free to submit issues or pull requests.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzakirkun%2Fdy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzakirkun%2Fdy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzakirkun%2Fdy/lists"}