{"id":46496089,"url":"https://github.com/corvax/slogtfmt","last_synced_at":"2026-03-06T12:03:17.857Z","repository":{"id":246773681,"uuid":"822416615","full_name":"corvax/slogtfmt","owner":"corvax","description":"A handler for slog that allows you to customize timestamp formats.","archived":false,"fork":false,"pushed_at":"2025-11-28T03:30:09.000Z","size":23,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-11-30T15:22:15.984Z","etag":null,"topics":["go","golang","logger","slog","slog-handler"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/corvax.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","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,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-07-01T05:46:49.000Z","updated_at":"2025-11-28T03:28:15.000Z","dependencies_parsed_at":null,"dependency_job_id":"88956e33-fbd4-4d9f-855a-af11e3d65c5c","html_url":"https://github.com/corvax/slogtfmt","commit_stats":null,"previous_names":["corvax/slogtfmt"],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/corvax/slogtfmt","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/corvax%2Fslogtfmt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/corvax%2Fslogtfmt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/corvax%2Fslogtfmt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/corvax%2Fslogtfmt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/corvax","download_url":"https://codeload.github.com/corvax/slogtfmt/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/corvax%2Fslogtfmt/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30175911,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-06T11:48:51.886Z","status":"ssl_error","status_checked_at":"2026-03-06T11:48:51.460Z","response_time":250,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["go","golang","logger","slog","slog-handler"],"created_at":"2026-03-06T12:03:11.797Z","updated_at":"2026-03-06T12:03:17.847Z","avatar_url":"https://github.com/corvax.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# slogtfmt\n\n`slogtfmt` is a handler for slog that allows you to customize timestamp formats for both log timestamps and time attributes. This package also provides a helper function to add tags to log entries.\n\n## Features\n\n- Customizable time value formatting for both log timestamps and time attributes\n- Support for log record tagging, tags are shown in square brackets before the message\n- Optional inclusion of source code information (file and line number)\n\n## Installation\n\nTo install `slogtfmt`, use `go get`:\n\n```bash\ngo get github.com/corvax/slogtfmt\n```\n## Usage\n\n### Creating a New Handler\n\nTo create a new slog handler, use the `NewHandler` function. This function requires an `io.Writer` where the logs will be written and an `Options` struct to configure the handler.\n\n```go\npackage main\n\nimport (\n\t\"time\"\n\t\"os\"\n\t\"github.com/corvax/slogtfmt\"\n)\n\nfunc main() {\n\topts := \u0026slogtfmt.Options{\n\t\tLevel:               slog.LevelInfo,\n\t\tAddSource:           false,\n\t\tTimeFormat:          \"2006-01-02T15:04:05.999Z07:00\",\n\t\tTimeInUTC:           true,\n\t\tTimeAttributeFormat: time.RFC3339,\n\t\tTimeAttributeInUTC:  true,\n\t}\n\n\tlogger := slog.New(slogtfmt.NewHandler(os.Stdout, opts))\n\tslog.SetDefault(logger)\n\tslog.Info(\"Started\", slog.Time(\"time\", time.Now()))\n\n\t// To create a logger with an added tag, use With(slogtfmt.Tag(\"tag_name\")\n\tserviceLogger := logger.With(slogtfmt.Tag(\"service\"))\n\tserviceLogger.Info(\"Started\")\n}\n```\n\n#### Sample output\n\nThe output of the sample code above would be as following:\n\n```text\n2024-07-01T04:23:30.557Z    INFO    Started time=2024-07-01T03:41:05Z\n2024-07-01T04:23:30.557Z    INFO    [service]     Started\n```\n\n### Without a timestamp\n\nIn order to omit the log timestamp, set `TimeFormat` to an empty string.\n\n```go\n\topts := \u0026slogtfmt.Options{\n\t\tLevel:      slog.LevelDebug,\n\t\tTimeFormat: \"\",\n\t}\n\n\tslog.SetDefault(slog.New(slogtfmt.NewHandler(os.Stdout, opts)))\n\n\tslog.Info(\"Started\", slog.Time(\"time\", time.Now())\n\tslog.Debug(\"User connected\", slog.String(\"user\", \"username\"))\n\tslog.Warn(\"Access denied\", slog.String(\"role\", \"readOnly\"))\n \tslog.Error(\"Service is unavailable\")\n \tslog.Info(\"Finished\")\n```\n\n#### Output:\n\nNote that the time attribute format is not affected and uses the default formatting `slogtfmt.RFC3339Milli`.\n```\nINFO\tStarted time=2024-07-01T15:02:50.720+10:00\nDEBUG\tUser connected user=\"username\"\nWARN\tAccess denied role=\"readOnly\"\nERROR\tService is unavailable\nINFO\tFinished\n```\n\n### Using `With` Option functions\n\nYou can also use the `slogtfmt.NewHandlerWithOptions()` constructor with Option functions.\n\nTo achieve the same log formatting as shown above, you can use the following snippet:\n\n```go\nslog.SetDefault(slog.New(slogtfmt.NewHandlerWithOptions(\n\tos.Stdout,\n\tslogtfmt.WithLevel(slog.LevelDebug),\n\tslogtfmt.WithTimeFormat(\"\"),\n)))\n```\n\n`With` functions are available for all `Options`.\n\n### Default options\n\nThe constructor `slogtfmt.NewHandlerWithOptions()` creates the handler with the default `Options` and then updates them using the provided `With` option functions.\n\nIf `nil` as `Options` is passed to `slogtfmt.NewHandler()`, the handler will be created with the default options.\n\n##### Default options\n\n```go\ndefaultOptions := \u0026Options{\n\tLevel:               slog.LevelInfo,\n\tAddSource:           false,\n\tTimeFormat:          slogtfmt.RFC3339Milli,\n\tTimeInUTC:           false,\n\tTimeAttributeFormat: slogtfmt.RFC3339Milli,\n\tTimeAttributeInUTC:  false,\n}\n```\n\n## Time formats\n\nIn addition to the standard time format, there are some additional time formats available in the package that can be used for formatting timestamps.\n\n```go\nconst (\n\tRFC3339Milli = \"2006-01-02T15:04:05.000Z07:00\"\n\tRFC3339Micro = \"2006-01-02T15:04:05.000000Z07:00\"\n)\n\n```\n\n## Options\n\nThe `Options` struct allows you to customize the behavior of the handler. Below is a detailed explanation of each field in the `Options` struct:\n\n* **`Level`**: Specifies the minimum level to log. Logs with a lower level are discarded. If `nil`, the handler uses `slog.LevelInfo`.\n* **`AddSource`**: If set to `true`, the handler computes the source code position of the log statement and adds the file name and the position to the output.\n* **`TimeFormat`**: The format used for log timestamps in the output. If empty, the handler will omit the timestamps.\n* **`TimeInUTC`**: Specifies whether the time format should use UTC instead of the local time zone.\n* **`TimeAttributeFormat`**: Specifies the time format used for the time attribute in the log record. If empty, the default time format of `time.RFC3339` is used.\n* **`TimeAttributeInUTC`**: Specifies whether the time attribute in the log record should use UTC instead of the local time zone.\n\n## `loggerf.Logger`\n\nThe `loggerf.Logger` is a wrapper around the standard `slog.Logger` structure that provides additional functions to format log messages. These functions allow you to log messages with formatted strings, similar to `fmt.Printf`.\n\n### Formatting functions\n\nThe `loggerf.Logger` provides the following functions to format the log message:\n\n- `Debugf(format string, args ...any)`: Log a debug message with formatting.\n- `Infof(format string, args ...any)`: Log an info message with formatting.\n- `Warnf(format string, args ...any)`: Log a warning message with formatting.\n- `Errorf(format string, args ...any)`: Log an error message with formatting.\n- `Logf(ctx context.Context, level slog.Level, format string, args ...any)`: Log a formatted message at the specified log level.\n\n### Usage\n\nTo use the `loggerf.Logger`, add the `loggerf` import to your code:\n\n```bash\ngo get github.com/corvax/slogtfmt/loggerf\n```\n\nCreate a new instance of `loggerf.Logger` based on any `slog.Logger`:\n\n```go\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"os\"\n\n\t\"github.com/corvax/slogtfmt\"\n\t\"github.com/corvax/slogtfmt/loggerf\"\n)\n\nfunc main() {\n\thandler := slogtfmt.NewHandler(os.Stdout, \u0026slogtfmt.Options{\n\t\tLevel:      slog.LevelDebug,\n\t\tTimeFormat: \"\",\n\t})\n\tslogger := slog.New(handler)\n\tlogger := loggerf.NewLogger(slogger)\n\n\t// Now you can use the functions to format the log messages.\n\t// For example:\n\tusername := \"user\"\n\tipAddress := \"localhost\"\n\tdiskUsage := 98\n\terr := errors.New(\"test error\")\n\n\tlogger.Debugf(\"Debug message: %s\", \"Hello, World!\")\n\tlogger.Infof(\"User %s logged in from %s\", username, ipAddress)\n\tlogger.Warnf(\"Warning: disk usage is at %d%%\", diskUsage)\n\tlogger.Errorf(\"Error occurred: %v\", err)\n}\n```\n\nOutput:\n```\nDEBUG   Debug message: Hello, World!\nINFO    User user logged in from localhost\nWARN    Warning: disk usage is at 98%\nERROR   Error occured: test error\n```\n\n### With context\n\nYou can also create a new logger with additional context using the `With` method:\n\n```go\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"os\"\n\n\t\"github.com/corvax/slogtfmt\"\n\t\"github.com/corvax/slogtfmt/loggerf\"\n)\n\nfunc main() {\n\thandler := slogtfmt.NewHandler(os.Stdout, \u0026slogtfmt.Options{\n\t\tLevel:      slog.LevelDebug,\n\t\tTimeFormat: \"\",\n\t})\n\tslogger := slog.New(handler)\n\tlogger := loggerf.NewLogger(slogger.With(slogtfmt.Tag(\"service\")))\n\n\t// Now you can use the functions to format the log message.\n\t// For example:\n\tusername := \"user\"\n\tipAddress := \"localhost\"\n\tdiskUsage := 98\n\terr := errors.New(\"test error\")\n\n\tlogger.Debugf(\"Debug message: %s\", \"Hello, World!\")\n\tlogger.Infof(\"User %s logged in from %s\", username, ipAddress)\n\tlogger.Warnf(\"Warning: disk usage is at %d%%\", diskUsage)\n\tlogger.Errorf(\"Error occurred: %v\", err)\n}\n```\n\nOutput:\n```\nDEBUG   [service]\tDebug message: Hello, World!\nINFO    [service]\tUser user logged in from localhost\nWARN    [service]\tWarning: disk usage is at 98%\nERROR   [service]\tError occured: test error\n```\n\n`WithGroup` can also be used to create a new logger with additional context and a group name.\n\n### Notes\n\nPlease be aware that the formatting log message functions use `args` to format the message. `args` values are not used to build `slog.Attr`.\n\nIf you want to add additional attributes to your log message, you can still use the `slog.Logger` methods, for example:\n\n```go\nlogger.Info(\"User is logged in\", \"username\", username, \"host\", ipAddress)\n```\n\nOutput:\n```\nINFO    User is logged in username=\"user\" host=\"localhost\"\n```\n\n`loggerf.Logger` embeds the `slog.Logger` structure, so you can use any of the `slog.Logger` methods.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcorvax%2Fslogtfmt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcorvax%2Fslogtfmt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcorvax%2Fslogtfmt/lists"}