You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

logging-documentation.en-us.md 20 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. ---
  2. date: "2019-04-02T17:06:00+01:00"
  3. title: "Advanced: Logging Configuration"
  4. slug: "logging-configuration"
  5. weight: 55
  6. toc: false
  7. draft: false
  8. menu:
  9. sidebar:
  10. parent: "advanced"
  11. name: "Logging Configuration"
  12. weight: 55
  13. identifier: "logging-configuration"
  14. ---
  15. # Logging Configuration
  16. The logging framework has been revamped in Gitea 1.9.0.
  17. **Table of Contents**
  18. {{< toc >}}
  19. ## Log Groups
  20. The fundamental thing to be aware of in Gitea is that there are several
  21. log groups:
  22. - The "Default" logger
  23. - The Macaron logger
  24. - The Router logger
  25. - The Access logger
  26. - The XORM logger
  27. There is also the go log logger.
  28. ### The go log logger
  29. Go provides its own extremely basic logger in the `log` package,
  30. however, this is not sufficient for our purposes as it does not provide
  31. a way of logging at multiple levels, nor does it provide a good way of
  32. controlling where these logs are logged except through setting of a
  33. writer.
  34. We have therefore redirected this logger to our Default logger, and we
  35. will log anything that is logged using the go logger at the INFO level.
  36. ### The "Default" logger
  37. Calls to `log.Info`, `log.Debug`, `log.Error` etc. from the `code.gitea.io/gitea/modules/log` package will log to this logger.
  38. You can configure the outputs of this logger by setting the `MODE`
  39. value in the `[log]` section of the configuration.
  40. Each output sublogger is configured in a separate `[log.sublogger.default]`
  41. which inherits from the sublogger `[log.sublogger]` section and from the
  42. generic `[log]` section, but there are certain default values. These will
  43. not be inherited from the `[log]` section:
  44. - `FLAGS` is `stdflags` (Equal to
  45. `date,time,medfile,shortfuncname,levelinitial`)
  46. - `FILE_NAME` will default to `%(ROOT_PATH)/gitea.log`
  47. - `EXPRESSION` will default to `""`
  48. - `PREFIX` will default to `""`
  49. The provider type of the sublogger can be set using the `MODE` value in
  50. its subsection, but will default to the name. This allows you to have
  51. multiple subloggers that will log to files.
  52. ### The "Macaron" logger
  53. By default Macaron will log to its own go `log` instance. This writes
  54. to `os.Stdout`. You can redirect this log to a Gitea configurable logger
  55. through setting the `REDIRECT_MACARON_LOG` setting in the `[log]`
  56. section which you can configure the outputs of by setting the `MACARON`
  57. value in the `[log]` section of the configuration. `MACARON` defaults
  58. to `file` if unset.
  59. Please note, the macaron logger will log at `INFO` level, setting the
  60. `LEVEL` of this logger to `WARN` or above will result in no macaron logs.
  61. Each output sublogger for this logger is configured in
  62. `[log.sublogger.macaron]` sections. There are certain default values
  63. which will not be inherited from the `[log]` or relevant
  64. `[log.sublogger]` sections:
  65. - `FLAGS` is `stdflags` (Equal to
  66. `date,time,medfile,shortfuncname,levelinitial`)
  67. - `FILE_NAME` will default to `%(ROOT_PATH)/macaron.log`
  68. - `EXPRESSION` will default to `""`
  69. - `PREFIX` will default to `""`
  70. NB: You can redirect the macaron logger to send its events to the gitea
  71. log using the value: `MACARON = ,`
  72. ### The "Router" logger
  73. There are two types of Router log. By default Macaron send its own
  74. router log which will be directed to Macaron's go `log`, however if you
  75. `REDIRECT_MACARON_LOG` you will enable Gitea's router log. You can
  76. disable both types of Router log by setting `DISABLE_ROUTER_LOG`.
  77. If you enable the redirect, you can configure the outputs of this
  78. router log by setting the `ROUTER` value in the `[log]` section of the
  79. configuration. `ROUTER` will default to `console` if unset. The Gitea
  80. Router logs the same data as the Macaron log but has slightly different
  81. coloring. It logs at the `Info` level by default, but this can be
  82. changed if desired by setting the `ROUTER_LOG_LEVEL` value.
  83. Please note, setting the `LEVEL` of this logger to a level above
  84. `ROUTER_LOG_LEVEL` will result in no router logs.
  85. Each output sublogger for this logger is configured in
  86. `[log.sublogger.router]` sections. There are certain default values
  87. which will not be inherited from the `[log]` or relevant
  88. `[log.sublogger]` sections:
  89. - `FILE_NAME` will default to `%(ROOT_PATH)/router.log`
  90. - `FLAGS` defaults to `date,time`
  91. - `EXPRESSION` will default to `""`
  92. - `PREFIX` will default to `""`
  93. NB: You can redirect the router logger to send its events to the Gitea
  94. log using the value: `ROUTER = ,`
  95. ### The "Access" logger
  96. The Access logger is a new logger for version 1.9. It provides a NCSA
  97. Common Log compliant log format. It's highly configurable but caution
  98. should be taken when changing its template. The main benefit of this
  99. logger is that Gitea can now log accesses in a standard log format so
  100. standard tools may be used.
  101. You can enable this logger using `ENABLE_ACCESS_LOG`. Its outputs are
  102. configured by setting the `ACCESS` value in the `[log]` section of the
  103. configuration. `ACCESS` defaults to `file` if unset.
  104. Each output sublogger for this logger is configured in
  105. `[log.sublogger.access]` sections. There are certain default values
  106. which will not be inherited from the `[log]` or relevant
  107. `[log.sublogger]` sections:
  108. - `FILE_NAME` will default to `%(ROOT_PATH)/access.log`
  109. - `FLAGS` defaults to `` or None
  110. - `EXPRESSION` will default to `""`
  111. - `PREFIX` will default to `""`
  112. If desired the format of the Access logger can be changed by changing
  113. the value of the `ACCESS_LOG_TEMPLATE`.
  114. Please note, the access logger will log at `INFO` level, setting the
  115. `LEVEL` of this logger to `WARN` or above will result in no access logs.
  116. NB: You can redirect the access logger to send its events to the Gitea
  117. log using the value: `ACCESS = ,`
  118. #### The ACCESS_LOG_TEMPLATE
  119. This value represent a go template. It's default value is:
  120. `{{.Ctx.RemoteAddr}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}\" \"{{.Ctx.Req.UserAgent}}"`
  121. The template is passed following options:
  122. - `Ctx` is the `macaron.Context`
  123. - `Identity` is the `SignedUserName` or `"-"` if the user is not logged
  124. in
  125. - `Start` is the start time of the request
  126. - `ResponseWriter` is the `macaron.ResponseWriter`
  127. Caution must be taken when changing this template as it runs outside of
  128. the standard panic recovery trap. The template should also be as simple
  129. as it runs for every request.
  130. ### The "XORM" logger
  131. The XORM logger is a long-standing logger that exists to collect XORM
  132. log events. It is enabled by default but can be switched off by setting
  133. `ENABLE_XORM_LOG` to `false` in the `[log]` section. Its outputs are
  134. configured by setting the `XORM` value in the `[log]` section of the
  135. configuration. `XORM` defaults to `,` if unset, meaning it is redirected
  136. to the main Gitea log.
  137. XORM will log SQL events by default. This can be changed by setting
  138. the `LOG_SQL` value to `false` in the `[database]` section.
  139. Each output sublogger for this logger is configured in
  140. `[log.sublogger.xorm]` sections. There are certain default values
  141. which will not be inherited from the `[log]` or relevant
  142. `[log.sublogger]` sections:
  143. - `FILE_NAME` will default to `%(ROOT_PATH)/xorm.log`
  144. - `FLAGS` defaults to `date,time`
  145. - `EXPRESSION` will default to `""`
  146. - `PREFIX` will default to `""`
  147. ## Log outputs
  148. Gitea provides 4 possible log outputs:
  149. - `console` - Log to `os.Stdout` or `os.Stderr`
  150. - `file` - Log to a file
  151. - `conn` - Log to a keep-alive TCP connection
  152. - `smtp` - Log via email
  153. Certain configuration is common to all modes of log output:
  154. - `LEVEL` is the lowest level that this output will log. This value
  155. is inherited from `[log]` and in the case of the non-default loggers
  156. from `[log.sublogger]`.
  157. - `STACKTRACE_LEVEL` is the lowest level that this output will print
  158. a stacktrace. This value is inherited.
  159. - `MODE` is the mode of the log output. It will default to the sublogger
  160. name. Thus `[log.console.macaron]` will default to `MODE = console`.
  161. - `COLORIZE` will default to `true` for `console` as
  162. described, otherwise it will default to `false`.
  163. ### Non-inherited default values
  164. There are several values which are not inherited as described above but
  165. rather default to those specific to type of logger, these are:
  166. `EXPRESSION`, `FLAGS`, `PREFIX` and `FILE_NAME`.
  167. #### `EXPRESSION`
  168. `EXPRESSION` represents a regular expression that log events must match to be logged by the sublogger. Either the log message, (with colors removed), must match or the `longfilename:linenumber:functionname` must match. NB: the whole message or string doesn't need to completely match.
  169. Please note this expression will be run in the sublogger's goroutine
  170. not the logging event subroutine. Therefore it can be complicated.
  171. #### `FLAGS`
  172. `FLAGS` represents the preceding logging context information that is
  173. printed before each message. It is a comma-separated string set. The order of values does not matter.
  174. Possible values are:
  175. - `none` or `,` - No flags.
  176. - `date` - the date in the local time zone: `2009/01/23`.
  177. - `time` - the time in the local time zone: `01:23:23`.
  178. - `microseconds` - microsecond resolution: `01:23:23.123123`. Assumes
  179. time.
  180. - `longfile` - full file name and line number: `/a/b/c/d.go:23`.
  181. - `shortfile` - final file name element and line number: `d.go:23`.
  182. - `funcname` - function name of the caller: `runtime.Caller()`.
  183. - `shortfuncname` - last part of the function name. Overrides
  184. `funcname`.
  185. - `utc` - if date or time is set, use UTC rather than the local time
  186. zone.
  187. - `levelinitial` - Initial character of the provided level in brackets eg. `[I]` for info.
  188. - `level` - Provided level in brackets `[INFO]`
  189. - `medfile` - Last 20 characters of the filename - equivalent to
  190. `shortfile,longfile`.
  191. - `stdflags` - Equivalent to `date,time,medfile,shortfuncname,levelinitial`
  192. ### Console mode
  193. For loggers in console mode, `COLORIZE` will default to `true` if not
  194. on windows, or the windows terminal can be set into ANSI mode or is a
  195. cygwin or Msys pipe.
  196. If `STDERR` is set to `true` the logger will use `os.Stderr` instead of
  197. `os.Stdout`.
  198. ### File mode
  199. The `FILE_NAME` defaults as described above. If set it will be relative
  200. to the provided `ROOT_PATH` in the master `[log]` section.
  201. Other values:
  202. - `LOG_ROTATE`: **true**: Rotate the log files.
  203. - `MAX_SIZE_SHIFT`: **28**: Maximum size shift of a single file, 28 represents 256Mb.
  204. - `DAILY_ROTATE`: **true**: Rotate logs daily.
  205. - `MAX_DAYS`: **7**: Delete the log file after n days
  206. - `COMPRESS`: **true**: Compress old log files by default with gzip
  207. - `COMPRESSION_LEVEL`: **-1**: Compression level
  208. ### Conn mode
  209. - `RECONNECT_ON_MSG`: **false**: Reconnect host for every single message.
  210. - `RECONNECT`: **false**: Try to reconnect when connection is lost.
  211. - `PROTOCOL`: **tcp**: Set the protocol, either "tcp", "unix" or "udp".
  212. - `ADDR`: **:7020**: Sets the address to connect to.
  213. ### SMTP mode
  214. It is not recommended to use this logger to send general logging
  215. messages. However, you could perhaps set this logger to work on `FATAL`.
  216. - `USER`: User email address to send from.
  217. - `PASSWD`: Password for the smtp server.
  218. - `HOST`: **127.0.0.1:25**: The SMTP host to connect to.
  219. - `RECEIVERS`: Email addresses to send to.
  220. - `SUBJECT`: **Diagnostic message from Gitea**
  221. ## Debugging problems
  222. When submitting logs in Gitea issues it is often helpful to submit
  223. merged logs obtained by either by redirecting the console log to a file or
  224. copying and pasting it. To that end it is recommended to set your logging to:
  225. ```ini
  226. [database]
  227. LOG_SQL = false ; SQL logs are rarely helpful unless we specifically ask for them
  228. ...
  229. [log]
  230. MODE = console
  231. LEVEL = debug ; please set the level to debug when we are debugging a problem
  232. REDIRECT_MACARON_LOG = true
  233. MACARON = console
  234. ROUTER = console
  235. COLORIZE = false ; this can be true if you can strip out the ansi coloring
  236. ```
  237. Sometimes it will be helpful get some specific `TRACE` level logging retricted
  238. to messages that match a specific `EXPRESSION`. Adjusting the `MODE` in the
  239. `[log]` section to `MODE = console,traceconsole` to add a new logger output
  240. `traceconsole` and then adding its corresponding section would be helpful:
  241. ```ini
  242. [log.traceconsole] ; traceconsole here is just a name
  243. MODE = console ; this is the output that the traceconsole writes to
  244. LEVEL = trace
  245. EXPRESSION = ; putting a string here will restrict this logger to logging only those messages that match this expression
  246. ```
  247. (It's worth noting that log messages that match the expression at or above debug
  248. level will get logged twice so don't worry about that.)
  249. `STACKTRACE_LEVEL` should generally be left unconfigured (and hence kept at
  250. `none`). There are only very specific occasions when it useful.
  251. ## Empty Configuration
  252. The empty configuration is equivalent to:
  253. ```ini
  254. [log]
  255. ROOT_PATH = %(GITEA_WORK_DIR)/log
  256. MODE = console
  257. LEVEL = Info
  258. STACKTRACE_LEVEL = None
  259. REDIRECT_MACARON_LOG = false
  260. ENABLE_ACCESS_LOG = false
  261. ENABLE_XORM_LOG = true
  262. XORM = ,
  263. [log.console]
  264. MODE = console
  265. LEVEL = %(LEVEL)
  266. STACKTRACE_LEVEL = %(STACKTRACE_LEVEL)
  267. FLAGS = stdflags
  268. PREFIX =
  269. COLORIZE = true # Or false if your windows terminal cannot color
  270. ```
  271. This is equivalent to sending all logs to the console, with default go log being sent to the console log too.
  272. ## Releasing-and-Reopening, Pausing and Resuming logging
  273. If you are running on Unix you may wish to release-and-reopen logs in order to use `logrotate` or other tools.
  274. It is possible force gitea to release and reopen it's logging files and connections by sending `SIGUSR1` to the
  275. running process, or running `gitea manager logging release-and-reopen`.
  276. Alternatively, you may wish to pause and resume logging - this can be accomplished through the use of the
  277. `gitea manager logging pause` and `gitea manager logging resume` commands. Please note that whilst logging
  278. is paused log events below INFO level will not be stored and only a limited number of events will be stored.
  279. Logging may block, albeit temporarily, slowing gitea considerably whilst paused - therefore it is
  280. recommended that pausing only done for a very short period of time.
  281. ## Adding and removing logging whilst Gitea is running
  282. It is possible to add and remove logging whilst Gitea is running using the `gitea manager logging add` and `remove` subcommands.
  283. This functionality can only adjust running log systems and cannot be used to start the access, macaron or router loggers if they
  284. were not already initialised. If you wish to start these systems you are advised to adjust the app.ini and (gracefully) restart
  285. the Gitea service.
  286. The main intention of these commands is to easily add a temporary logger to investigate problems on running systems where a restart
  287. may cause the issue to disappear.
  288. ## Log colorization
  289. Logs to the console will be colorized by default when not running on
  290. Windows. Terminal sniffing will occur on Windows and if it is
  291. determined that we are running on a terminal capable of color we will
  292. colorize.
  293. Further, on \*nix it is becoming common to have file logs that are
  294. colored by default. Therefore file logs will be colorised by default
  295. when not running on Windows.
  296. You can switch on or off colorization by using the `COLORIZE` value.
  297. From a development point of view. If you write
  298. `log.Info("A %s string", "formatted")` the `formatted` part of the log
  299. message will be Bolded on colorized logs.
  300. You can change this by either rendering the formatted string yourself.
  301. Or you can wrap the value in a `log.ColoredValue` struct.
  302. The `log.ColoredValue` struct contains a pointer to value, a pointer to
  303. string of bytes which should represent a color and second set of reset
  304. bytes. Pointers were chosen to prevent copying of large numbers of
  305. values. There are several helper methods:
  306. - `log.NewColoredValue` takes a value and 0 or more color attributes
  307. that represent the color. If 0 are provided it will default to a cached
  308. bold. Note, it is recommended that color bytes constructed from
  309. attributes should be cached if this is a commonly used log message.
  310. - `log.NewColoredValuePointer` takes a pointer to a value, and
  311. 0 or more color attributes that represent the color.
  312. - `log.NewColoredValueBytes` takes a value and a pointer to an array
  313. of bytes representing the color.
  314. These functions will not double wrap a `log.ColoredValue`. They will
  315. also set the `resetBytes` to the cached `resetBytes`.
  316. The `colorBytes` and `resetBytes` are not exported to prevent
  317. accidental overwriting of internal values.
  318. ## ColorFormat & ColorFormatted
  319. Structs may implement the `log.ColorFormatted` interface by implementing the `ColorFormat(fmt.State)` function.
  320. If a `log.ColorFormatted` struct is logged with `%-v` format, its `ColorFormat` will be used instead of the usual `%v`. The full `fmt.State` will be passed to allow implementers to look at additional flags.
  321. In order to help implementers provide `ColorFormat` methods. There is a
  322. `log.ColorFprintf(...)` function in the log module that will wrap values in `log.ColoredValue` and recognise `%-v`.
  323. In general it is recommended not to make the results of this function too verbose to help increase its versatility. Usually this should simply be an `ID`:`Name`. If you wish to make a more verbose result, it is recommended to use `%-+v` as your marker.
  324. ## Log Spoofing protection
  325. In order to protect the logs from being spoofed with cleverly
  326. constructed messages. Newlines are now prefixed with a tab and control
  327. characters except those used in an ANSI CSI are escaped with a
  328. preceding `\` and their octal value.
  329. ## Creating a new named logger group
  330. Should a developer wish to create a new named logger, `NEWONE`. It is
  331. recommended to add an `ENABLE_NEWONE_LOG` value to the `[log]`
  332. section, and to add a new `NEWONE` value for the modes.
  333. A function like `func newNewOneLogService()` is recommended to manage
  334. construction of the named logger. e.g.
  335. ```go
  336. func newNewoneLogService() {
  337. EnableNewoneLog = Cfg.Section("log").Key("ENABLE_NEWONE_LOG").MustBool(false)
  338. Cfg.Section("log").Key("NEWONE").MustString("file") // or console? or "," if you want to send this to default logger by default
  339. if EnableNewoneLog {
  340. options := newDefaultLogOptions()
  341. options.filename = filepath.Join(LogRootPath, "newone.log")
  342. options.flags = "stdflags"
  343. options.bufferLength = Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000)
  344. generateNamedLogger("newone", options)
  345. }
  346. }
  347. ```
  348. You should then add `newOneLogService` to `NewServices()` in
  349. `modules/setting/setting.go`
  350. ## Using `logrotate` instead of built-in log rotation
  351. Gitea includes built-in log rotation, which should be enough for most deployments. However, if you instead want to use the `logrotate` utility:
  352. - Disable built-in log rotation by setting `LOG_ROTATE` to `false` in your `app.ini`.
  353. - Install `logrotate`.
  354. - Configure `logrotate` to match your deployment requirements, see `man 8 logrotate` for configuration syntax details. In the `postrotate/endscript` block send Gitea a `USR1` signal via `kill -USR1` or `kill -10`, or run `gitea manager logging release-and-reopen` (with the appropriate environment). Ensure that your configurations apply to all files emitted by Gitea loggers as described in the above sections.
  355. - Always do `logrotate /etc/logrotate.conf --debug` to test your configurations.
  356. The next `logrotate` jobs will include your configurations, so no restart is needed. You can also immediately reload `logrotate` with `logrotate /etc/logrotate.conf --force`.