log: journald integration (#2869)

Provide a bit more journald integration. Specifically:

- support emission of printk-style log level prefixes, documented in [`sd-daemon`(3)](https://man7.org/linux/man-pages/man3/sd-daemon.3.html#DESCRIPTION), that allow journald to automatically annotate stderr log lines with their level;
- add a new "journaldflags" item that is supposed to be used in place of "stdflags" when under journald to reduce log clutter (i. e. strip date/time info to avoid duplication, and use log level prefixes instead of textual log levels);
- detect whether stderr and/or stdout are attached to journald by parsing `$JOURNAL_STREAM` environment variable and adjust console logger defaults accordingly.

<!--start release-notes-assistant-->

## Draft release notes
<!--URL:https://codeberg.org/forgejo/forgejo-->
- Features
  - [PR](https://codeberg.org/forgejo/forgejo/pulls/2869): <!--number 2869 --><!--line 0 --><!--description bG9nOiBqb3VybmFsZCBpbnRlZ3JhdGlvbg==-->log: journald integration<!--description-->
<!--end release-notes-assistant-->

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/2869
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>
Co-authored-by: Ivan Shapovalov <intelfx@intelfx.name>
Co-committed-by: Ivan Shapovalov <intelfx@intelfx.name>
This commit is contained in:
Ivan Shapovalov 2024-08-09 07:49:13 +00:00 committed by Earl Warren
parent a72763f5a3
commit 012a1e0497
9 changed files with 169 additions and 18 deletions

View file

@ -39,6 +39,22 @@ var toString = map[Level]string{
NONE: "none",
}
// Machine-readable log level prefixes as defined in sd-daemon(3).
//
// "If a systemd service definition file is configured with StandardError=journal
// or StandardError=kmsg (and similar with StandardOutput=), these prefixes can
// be used to encode a log level in lines printed. <...> To use these prefixes
// simply prefix every line with one of these strings. A line that is not prefixed
// will be logged at the default log level SD_INFO."
var toJournalPrefix = map[Level]string{
TRACE: "<7>", // SD_DEBUG
DEBUG: "<6>", // SD_INFO
INFO: "<5>", // SD_NOTICE
WARN: "<4>", // SD_WARNING
ERROR: "<3>", // SD_ERR
FATAL: "<2>", // SD_CRIT
}
var toLevel = map[string]Level{
"undefined": UNDEFINED,
@ -71,6 +87,10 @@ func (l Level) String() string {
return "info"
}
func (l Level) JournalPrefix() string {
return toJournalPrefix[l]
}
func (l Level) ColorAttributes() []ColorAttribute {
color, ok := levelToColor[l]
if ok {