doc.go 10 KB

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