From 3f1a2cbd9327d2548481f21860bc6f8a78bfe575 Mon Sep 17 00:00:00 2001 From: mleku Date: Tue, 11 Jun 2024 18:43:17 +0100 Subject: [PATCH] initial commit --- .gitignore | 29 +++ .idea/.gitignore | 5 + .idea/lol.iml | 9 + .idea/material_theme_project_new.xml | 17 ++ .idea/modules.xml | 8 + .idea/vcs.xml | 6 + LICENSE | 121 +++++++++++++ README.md | 6 + go.mod | 14 ++ go.sum | 18 ++ log.go | 255 +++++++++++++++++++++++++++ log_test.go | 34 ++++ 12 files changed, 522 insertions(+) create mode 100644 .gitignore create mode 100644 .idea/.gitignore create mode 100644 .idea/lol.iml create mode 100644 .idea/material_theme_project_new.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 go.mod create mode 100644 go.sum create mode 100644 log.go create mode 100644 log_test.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..14feff3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Allowlisting gitignore template for GO projects prevents us +# from adding various unwanted local files, such as generated +# files, developer configurations or IDE-specific files etc. +# +# Recommended: Go.AllowList.gitignore + +# Ignore everything +* +# But not these files... +!/.gitignore +!*.go +!go.sum +!go.mod +!*.md +!LICENSE +!*.sh +!Makefile +!*.json +!*.pdf +!.codecov.yml +!*.bin +!*.py +!*.csv +!*.mediawiki +!*.png +!*.jpg +!*.svg +# ...even if they are in subdirectories +!*/ diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..b58b603 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,5 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ diff --git a/.idea/lol.iml b/.idea/lol.iml new file mode 100644 index 0000000..5e764c4 --- /dev/null +++ b/.idea/lol.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/material_theme_project_new.xml b/.idea/material_theme_project_new.xml new file mode 100644 index 0000000..e74fb91 --- /dev/null +++ b/.idea/material_theme_project_new.xml @@ -0,0 +1,17 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..e9893eb --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/README.md b/README.md new file mode 100644 index 0000000..8f535a3 --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +# lol + +location of log + +This is a very simple, but practical library for logging in applications. Its +main feature is printing source code locations to make debugging easier. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..fe012fd --- /dev/null +++ b/go.mod @@ -0,0 +1,14 @@ +module github.com/mleku/lol + +go 1.22.4 + +require ( + github.com/davecgh/go-spew v1.1.1 + github.com/gookit/color v1.5.4 + go.uber.org/atomic v1.11.0 +) + +require ( + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + golang.org/x/sys v0.21.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..7a32659 --- /dev/null +++ b/go.sum @@ -0,0 +1,18 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= +github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E= +golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= +golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/log.go b/log.go new file mode 100644 index 0000000..c5ddb2d --- /dev/null +++ b/log.go @@ -0,0 +1,255 @@ +package lol + +import ( + "fmt" + "io" + "os" + "runtime" + "strings" + "time" + + "github.com/davecgh/go-spew/spew" + "github.com/gookit/color" + "go.uber.org/atomic" +) + +var l = GetStd() + +func GetStd() (ll *Log) { + ll, _ = New(os.Stdout) + return +} + +func init() { + switch strings.ToUpper(os.Getenv("GODEBUG")) { + case "1", "TRUE", "ON": + SetLogLevel(Debug) + l.D.Ln("printing logs at this level and lower") + case "INFO": + SetLogLevel(Info) + case "DEBUG": + SetLogLevel(Debug) + l.D.Ln("printing logs at this level and lower") + case "TRACE": + SetLogLevel(Trace) + l.T.Ln("printing logs at this level and lower") + case "WARN": + SetLogLevel(Warn) + case "ERROR": + SetLogLevel(Error) + case "FATAL": + SetLogLevel(Fatal) + case "0", "OFF", "FALSE": + SetLogLevel(Off) + default: + SetLogLevel(Info) + } + +} + +const ( + Off = iota + Fatal + Error + Warn + Info + Debug + Trace +) + +type ( + // LevelPrinter defines a set of terminal printing primitives that output with + // extra data, time, log logLevelList, and code location + + // Ln prints lists of interfaces with spaces in between + Ln func(a ...interface{}) + // F prints like fmt.Println surrounded by log details + F func(format string, a ...interface{}) + // S prints a spew.Sdump for an interface slice + S func(a ...interface{}) + // C accepts a function so that the extra computation can be avoided if it is + // not being viewed + C func(closure func() string) + // Chk is a shortcut for printing if there is an error, or returning true + Chk func(e error) bool + // Err is a pass-through function that uses fmt.Errorf to construct an error + // and returns the error after printing it to the log + Err func(format string, a ...interface{}) error + LevelPrinter struct { + Ln + F + S + C + Chk + Err + } + LevelSpec struct { + ID int + Name string + Colorizer func(a ...interface{}) string + } + + // Entry is a log entry to be printed as json to the log file + Entry struct { + Time time.Time + Level string + Package string + CodeLocation string + Text string + } +) + +var ( + // sep is just a convenient shortcut for this very longwinded expression + sep = string(os.PathSeparator) + currentLevel = atomic.NewInt32(Info) + // writer can be swapped out for any io.*writer* that you want to use instead of + // stdout. + writer io.Writer = os.Stderr + // LevelSpecs specifies the id, string name and color-printing function + LevelSpecs = []LevelSpec{ + {Off, " ", color.Bit24(0, 0, 0, false).Sprint}, + {Fatal, "FTL", color.Bit24(128, 0, 0, false).Sprint}, + {Error, "ERR", color.Bit24(255, 0, 0, false).Sprint}, + {Warn, "WRN", color.Bit24(0, 255, 0, false).Sprint}, + {Info, "INF", color.Bit24(255, 255, 0, false).Sprint}, + {Debug, "DBG", color.Bit24(0, 125, 255, false).Sprint}, + {Trace, "TRC", color.Bit24(125, 0, 255, false).Sprint}, + } +) + +// Log is a set of log printers for the various Level items. +type Log struct { + F, E, W, I, D, T LevelPrinter +} + +type Check struct { + F, E, W, I, D, T Chk +} + +func JoinStrings(a ...any) (s string) { + for i := range a { + s += fmt.Sprint(a[i]) + if i < len(a)-1 { + s += " " + } + } + return +} + +func GetPrinter(l int32, writer io.Writer) LevelPrinter { + return LevelPrinter{ + Ln: func(a ...interface{}) { + fmt.Fprintf(writer, + "%s %s %s %s\n", + UnixNanoAsFloat(), + LevelSpecs[l].Colorizer(LevelSpecs[l].Name), + JoinStrings(a...), + GetLoc(2), + ) + }, + F: func(format string, a ...interface{}) { + fmt.Fprintf(writer, + "%s %s %s %s\n", + UnixNanoAsFloat(), + LevelSpecs[l].Colorizer(LevelSpecs[l].Name), + fmt.Sprintf(format, a...), + GetLoc(2), + ) + }, + S: func(a ...interface{}) { + fmt.Fprintf(writer, + "%s %s %s %s\n", + UnixNanoAsFloat(), + LevelSpecs[l].Colorizer(LevelSpecs[l].Name), + spew.Sdump(a...), + GetLoc(2), + ) + }, + C: func(closure func() string) { + fmt.Fprintf(writer, + "%s %s %s %s\n", + UnixNanoAsFloat(), + LevelSpecs[l].Colorizer(LevelSpecs[l].Name), + closure(), + GetLoc(2), + ) + }, + Chk: func(e error) bool { + if e != nil { + fmt.Fprintf(writer, + "%s %s %s %s\n", + UnixNanoAsFloat(), + LevelSpecs[l].Colorizer(LevelSpecs[l].Name), + e.Error(), + GetLoc(2), + ) + return true + } + return false + }, + Err: func(format string, a ...interface{}) error { + fmt.Fprintf(writer, + "%s %s %s %s\n", + UnixNanoAsFloat(), + LevelSpecs[l].Colorizer(LevelSpecs[l].Name, " "), + fmt.Sprintf(format, a...), + GetLoc(2), + ) + return fmt.Errorf(format, a...) + }, + } +} + +func New(writer io.Writer) (l *Log, c *Check) { + l = &Log{ + F: GetPrinter(Fatal, writer), + E: GetPrinter(Error, writer), + W: GetPrinter(Warn, writer), + I: GetPrinter(Info, writer), + D: GetPrinter(Debug, writer), + T: GetPrinter(Trace, writer), + } + c = &Check{ + F: l.F.Chk, + E: l.E.Chk, + W: l.W.Chk, + I: l.I.Chk, + D: l.D.Chk, + T: l.T.Chk, + } + return +} + +// SetLogLevel sets the log level via a string, which can be truncated down to +// one character, similar to nmcli's argument processor, as the first letter is +// unique. This could be used with a linter to make larger command sets. +func SetLogLevel(l int) { + currentLevel.Store(int32(l)) +} + +func GetLogLevel() (l int) { + return int(currentLevel.Load()) +} + +// UnixNanoAsFloat e +func UnixNanoAsFloat() (s string) { + timeText := fmt.Sprint(time.Now().UnixNano()) + lt := len(timeText) + lb := lt + 1 + var timeBytes = make([]byte, lb) + copy(timeBytes[lb-9:lb], timeText[lt-9:lt]) + timeBytes[lb-10] = '.' + lb -= 10 + lt -= 9 + copy(timeBytes[:lb], timeText[:lt]) + return color.Bit24(0, 128, 255, false).Sprint(string(timeBytes)) +} + +func GetLoc(skip int) (output string) { + _, file, line, _ := runtime.Caller(skip) + output = color.Bit24(0, 128, 255, false).Sprint( + file, ":", line, + ) + return +} diff --git a/log_test.go b/log_test.go new file mode 100644 index 0000000..700d952 --- /dev/null +++ b/log_test.go @@ -0,0 +1,34 @@ +package lol_test + +import ( + "errors" + "os" + "testing" + + "github.com/mleku/lol" +) + +var log, chk = lol.New(os.Stdout) + +func TestGetLogger(t *testing.T) { + for i := 0; i < 100; i++ { + lol.SetLogLevel(lol.Trace) + log.T.Ln("testing log level", lol.LevelSpecs[lol.Trace].Name) + log.D.Ln("testing log level", lol.LevelSpecs[lol.Debug].Name) + log.I.Ln("testing log level", lol.LevelSpecs[lol.Info].Name) + log.W.Ln("testing log level", lol.LevelSpecs[lol.Warn].Name) + log.E.F("testing log level %s", lol.LevelSpecs[lol.Error].Name) + log.F.Ln("testing log level", lol.LevelSpecs[lol.Fatal].Name) + chk.F(errors.New("dummy error as fatal")) + chk.E(errors.New("dummy error as error")) + chk.W(errors.New("dummy error as warning")) + chk.I(errors.New("dummy error as info")) + chk.D(errors.New("dummy error as debug")) + chk.T(errors.New("dummy error as trace")) + log.I.Ln("log.I.Err", + log.I.Err("format string %d '%s'", 5, "testing") != nil) + log.I.Chk(errors.New("dummy information check")) + log.I.Chk(nil) + log.I.S("`backtick wrapped string`", t) + } +}