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

423 lines
17 KiB

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