doc.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. /*
  2. CBSD 3-Clause License
  3. Copyright (c) 2017-2022, Gerasimos (Makis) Maropoulos (kataras2006@hotmail.com)
  4. All rights reserved.
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions are met:
  7. 1. Redistributions of source code must retain the above copyright notice, this
  8. list of conditions and the following disclaimer.
  9. 2. Redistributions in binary form must reproduce the above copyright notice,
  10. this list of conditions and the following disclaimer in the documentation
  11. and/or other materials provided with the distribution.
  12. 3. Neither the name of the copyright holder nor the names of its
  13. contributors may be used to endorse or promote products derived from
  14. this software without specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. /*
  26. Package golog provides an easy to use foundation for your logging operations.
  27. Source code and other details for the project are available at GitHub:
  28. https://github.com/kataras/golog
  29. # Current Version
  30. 0.1.11
  31. # Installation
  32. The only requirement is the Go Programming Language
  33. $ go get github.com/kataras/golog@latest
  34. # Overview
  35. Example code:
  36. package main
  37. import (
  38. "github.com/kataras/golog"
  39. )
  40. func main() {
  41. // Default Output is `os.Stdout`,
  42. // but you can change it:
  43. // golog.SetOutput(os.Stderr)
  44. // Time Format defaults to: "2006/01/02 15:04"
  45. // you can change it to something else or disable it with:
  46. golog.SetTimeFormat("")
  47. // Level defaults to "info",
  48. // but you can change it:
  49. golog.SetLevel("debug")
  50. golog.Println("This is a raw message, no levels, no colors.")
  51. golog.Info("This is an info message, with colors (if the output is terminal)")
  52. golog.Warn("This is a warning message")
  53. golog.Error("This is an error message")
  54. golog.Debug("This is a debug message")
  55. }
  56. # New
  57. Golog has a default, package-level initialized instance for you,
  58. however you can choose to create and use a logger instance for a
  59. specific part of your application.
  60. Example Code:
  61. package main
  62. import (
  63. "github.com/kataras/golog"
  64. )
  65. func main() {
  66. log := golog.New()
  67. // Default Output is `os.Stdout`,
  68. // but you can change it:
  69. // log.SetOutput(os.Stderr)
  70. // Level defaults to "info",
  71. // but you can change it:
  72. log.SetLevel("debug")
  73. log.Println("This is a raw message, no levels, no colors.")
  74. log.Info("This is an info message, with colors (if the output is terminal)")
  75. log.Warn("This is a warning message")
  76. log.Error("This is an error message")
  77. log.Debug("This is a debug message")
  78. }
  79. # Format
  80. Golog sets colors to levels when its `Printer.Output` is actual a compatible terminal
  81. which can renders colors, otherwise it will downgrade itself to a white foreground.
  82. Golog has functions to print a formatted log too.
  83. Example Code:
  84. golog.Infof("[%d] This is an info %s", 1, "formatted log")
  85. golog.Warnf("[%d] This is an info %s", 1, "formatted log")
  86. golog.Errorf("[%d] This is an info %s", 1, "formatted log")
  87. golog.Debugf("[%d] This is an info %s", 1, "formatted log")
  88. # Output
  89. Golog takes a simple `io.Writer` as its underline Printer's Output.
  90. Example Code:
  91. golog.SetOutput(io.Writer)
  92. You can even override the default line braker, "\n", by using the `golog#NewLine` function at startup.
  93. Example Code:
  94. golog.NewLine("\r\n")
  95. # Levels
  96. Golog is a leveled logger, therefore you can set a level and print
  97. whenever the print level is valid with the set-ed one.
  98. Available built'n levels are:
  99. // DisableLevel will disable printer
  100. DisableLevel Level = iota
  101. // ErrorLevel will print only errors
  102. ErrorLevel
  103. // WarnLevel will print errors and warnings
  104. WarnLevel
  105. // InfoLevel will print errors, warnings and infos
  106. InfoLevel
  107. // DebugLevel will print on any level, errors, warnings, infos and debug messages
  108. DebugLevel
  109. Below you'll learn a way to add a custom level or modify an existing level.
  110. The default colorful text(or raw text for unsupported outputs) for levels
  111. can be overridden by using the `golog#ErrorText, golog#WarnText, golog#InfoText and golog#DebugText`
  112. functions.
  113. Example Code:
  114. package main
  115. import (
  116. "github.com/kataras/golog"
  117. )
  118. func main() {
  119. // First argument is the raw text for outputs
  120. // second argument is the color code
  121. // and the last, variadic argument can be any `kataras/pio.RichOption`, e.g. pio.Background, pio.Underline.
  122. // Default is "[ERRO]"
  123. golog.ErrorText("|ERROR|", 31)
  124. // Default is "[WARN]"
  125. golog.WarnText("|WARN|", 32)
  126. // Default is "[INFO]"
  127. golog.InfoText("|INFO|", 34)
  128. // Default is "[DBUG]"
  129. golog.DebugText("|DEBUG|", 33)
  130. // Business as usual...
  131. golog.SetLevel("debug")
  132. golog.Println("This is a raw message, no levels, no colors.")
  133. golog.Info("This is an info message, with colors (if the output is terminal)")
  134. golog.Warn("This is a warning message")
  135. golog.Error("This is an error message")
  136. golog.Debug("This is a debug message")
  137. }
  138. Golog gives you the power to add or modify existing levels is via Level Metadata.
  139. Example Code:
  140. package main
  141. import (
  142. "github.com/kataras/golog"
  143. )
  144. func main() {
  145. // Let's add a custom level,
  146. //
  147. // It should be starting from level index 6,
  148. // because we have 6 built'n levels (0 is the start index):
  149. // disable,
  150. // fatal,
  151. // error,
  152. // warn,
  153. // info
  154. // debug
  155. // First we create our level to a golog.Level
  156. // in order to be used in the Log functions.
  157. var SuccessLevel golog.Level = 6
  158. // Register our level, just three fields.
  159. golog.Levels[SuccessLevel] = &golog.LevelMetadata{
  160. Name: "success",
  161. Title: "[SUCC]",
  162. ColorCode: 32, // Green
  163. }
  164. // create a new golog logger
  165. myLogger := golog.New()
  166. // set its level to the higher in order to see it
  167. // ("success" is the name we gave to our level)
  168. myLogger.SetLevel("success")
  169. // and finally print a log message with our custom level
  170. myLogger.Logf(SuccessLevel, "This is a success log message with green color")
  171. }
  172. The logger's level can be changed via passing one of the
  173. level constants to the `Level` field or by
  174. passing its string representation to the `SetLevel` function.
  175. Example Code:
  176. golog.SetLevel("disable")
  177. golog.SetLevel("fatal")
  178. golog.SetLevel("error")
  179. golog.SetLevel("warn")
  180. golog.SetLevel("info")
  181. golog.SetLevel("debug")
  182. # Integrations
  183. Transaction with your favorite, but deprecated logger is easy.
  184. Golog offers two basic interfaces, the `ExternalLogger` and the `StdLogger`
  185. that can be directly used as arguments to the `Install` function
  186. in order to adapt an external logger.
  187. Outline:
  188. // Install receives an external logger
  189. // and automatically adapts its print functions.
  190. //
  191. // Install adds a golog handler to support third-party integrations,
  192. // it can be used only once per `golog#Logger` instance.
  193. //
  194. // For example, if you want to print using a logrus
  195. // logger you can do the following:
  196. //
  197. // Install(logrus.StandardLogger())
  198. //
  199. // Or the standard log's Logger:
  200. //
  201. // import "log"
  202. // myLogger := log.New(os.Stdout, "", 0)
  203. // Install(myLogger)
  204. //
  205. // Or even the slog/log's Logger:
  206. //
  207. // import "log/slog"
  208. // myLogger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
  209. // Install(myLogger) OR Install(slog.Default())
  210. //
  211. // Look `golog#Logger.Handle` for more.
  212. Install(logger ExternalLogger)
  213. # Logrus Integration
  214. Example Code:
  215. package main
  216. import (
  217. "github.com/kataras/golog"
  218. "github.com/sirupsen/logrus"
  219. )
  220. func main() {
  221. // outputOnly()
  222. full()
  223. }
  224. func full() {
  225. // simulate a logrus preparation:
  226. logrus.SetLevel(logrus.InfoLevel)
  227. logrus.SetFormatter(&logrus.JSONFormatter{})
  228. // pass logrus.StandardLogger() to print logs using using the default,
  229. // package-level logrus' instance of Logger:
  230. golog.Install(logrus.StandardLogger())
  231. golog.Debug(`this debug message will not be shown,
  232. because the logrus level is InfoLevel`)
  233. golog.Error("this error message will be visible as json")
  234. // simulate a change of the logrus formatter
  235. // as you see we have nothing more to change
  236. // on the golog, it works out of the box,
  237. // it will be adapt by this change, automatically.
  238. logrus.SetFormatter(&logrus.TextFormatter{})
  239. golog.Error("this error message will be visible as text")
  240. golog.Info("this info message will be visible as text")
  241. }
  242. func outputOnly() {
  243. golog.SetOutput(logrus.StandardLogger().Out)
  244. golog.Info(`output only, this will print the same contents
  245. as golog but using the defined logrus' io.Writer`)
  246. golog.Error("this error message will be visible as text")
  247. }
  248. # Standard `log.Logger` Integration
  249. Example Code:
  250. package main
  251. import (
  252. "log"
  253. "os"
  254. "github.com/kataras/golog"
  255. )
  256. // simulate a log.Logger preparation:
  257. var myLogger = log.New(os.Stdout, "", 0)
  258. func main() {
  259. golog.SetLevel("error")
  260. golog.Install(myLogger)
  261. golog.Debug(`this debug message will not be shown,
  262. because the golog level is ErrorLevel`)
  263. golog.Error("this error message will be visible the only visible")
  264. golog.Warn("this info message will not be visible")
  265. }
  266. # That's the basics
  267. But you should have a basic idea of the golog package by now, we just scratched the surface.
  268. If you enjoy what you just saw and want to learn more, please follow the below links:
  269. Examples:
  270. https://github.com/kataras/golog/tree/master/_examples
  271. */
  272. package golog
  273. // Version is the version string representation of the "golog" package.
  274. const Version = "0.1.11"