Skip to content

log: replace clog with charmlog and logx - #8529

Merged
unknwon merged 20 commits into
mainfrom
logging/charmlog-logx
Nov 16, 2026
Merged

unknwon merged 20 commits into
mainfrom
logging/charmlog-logx

Conversation

@unknwon

@unknwon unknwon commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Describe the pull request

Replaces unknwon.dev/clog/v2 with charm.land/log/v2 as the slog handler and unknwon.dev/x/logx as the logger, the same pairing pgrok and git-lfs-server use. There is no wrapper package: loggers are *logx.Logger, and every call is structured, e.g., logger.Error("Failed to get user", "userID", id, "error", err). The handler setup lives in internal/conf/logging.go.

Configuration

  • [log] MODE still picks console, file, Slack, and Discord, each with its own level. A mode that does not set LEVEL now inherits [log] LEVEL, which the config comment already claimed and the old code did not do.
  • The default [log] LEVEL is now Debug. Trace is still accepted as the same level.
  • The new [log] FORMAT chooses the console and file output. Empty (the default) follows the run mode: JSON when RUN_MODE = prod, text otherwise. text or json overrides it, e.g., to keep text logs in production. The default config reads it from GOGS_LOG_FORMAT, which both Docker images set to json, and a user's own [log] FORMAT still wins.
  • File rotation for gogs.log is unchanged. SSH hook commands still write to log/hooks/ and never to the client.

Output

  • xorm and GORM log through the same logger, scoped as xorm and gorm, one structured line per query: sql, rows, elapsed, and source for GORM, sql and args for xorm. Long xorm arguments, such as webhook payloads, are truncated. Failed GORM queries are errors and slow ones are warnings, where a failed query used to be logged at debug level. xorm.log, gorm.log, and the [log.xorm] and [log.gorm] sections are gone.
  • A scoped logger records its scope in a component field, and nested scopes join with dots, e.g., db.gorm, so log explorers can filter by component and by prefix. Text output (console, file, hooks, Slack, and Discord) shows it as a [gorm] message prefix. This needs unknwon/x#2, which is merged.
  • Internal server errors log the request method and path. JSON timestamps are RFC 3339 with the time zone.

Text (default outside production):

2026-11-14 05:49:17 DEBU [lfs] Authorized user userName=smoke ownerName=smoke repoName=demo13079
2026-11-14 05:49:17 DEBU [gorm] Query sql="SELECT * FROM `user` WHERE lower_name = \"smoke\" ORDER BY `user`.`id` LIMIT 1" rows=1 elapsed=327.985µs source=/gogs/internal/database/users.go:719
2026-11-14 05:49:17 DEBU [xorm] Query sql="SELECT * FROM `pull_request` INNER JOIN issue ON issue.id = pull_request.issue_id WHERE (head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?)" args="[7, \"main\", false, false]"

JSON (default in production and in the Docker images):

{"time":"2026-11-14T05:50:35Z","level":"info","msg":"Server is available","externalURL":"http://localhost:3999/"}
{"time":"2026-11-16T19:01:47Z","level":"error","msg":"Query failed","component":"gorm","sql":"SELECT * FROM `access_token` WHERE uid = ? AND name = ? ORDER BY `access_token`.`id` LIMIT 1","rows":0,"elapsed":"41.837µs","source":"/gogs/internal/database/access_tokens.go:76","error":"SQL logic error: no such table: access_token (1)"}
{"time":"2026-11-14T05:50:46Z","level":"error","msg":"Internal server error","method":"POST","path":"/api/v1/user/repos","operation":"create repository","error":"initRepository: prepareRepoCommit: getRepoInitFile[]: unknown readme template \"\""}

Code

There is no global logger. Each command builds its logger and passes *logx.Logger down, after context.Context when there is one. Macaron and flamego have the logger mapped for injection, and macaron handlers also use c.Logger. The exception is methods whose signatures are fixed by xorm hooks or templates, which read the logger stored on the database handle. Loggers are scoped at the call site. AGENTS.md documents the argument order and scoping rules.

Differences from main

Some clog assumptions no longer hold, so these differ on purpose:

  • slog has no fatal level. FatalContext logs at the error level, and a handler raises those records to fatal, so sinks still show FATA and LEVEL = Fatal still receives only fatal records.
  • Slack and Discord post from a queue of BUFFER_LEN, like clog. clog drained the queue without limit before a fatal exit, and this waits at most 10 seconds. Console and file write synchronously, so BUFFER_LEN only applies to the webhooks.
  • SQL goes to the main log instead of xorm.log and gorm.log. The web server and serv log every query in dev mode. admin, backup, and restore only log failed and slow queries, so their console output does not fill with SQL. Query values appear only on the debug Query line, never on the error or warning for a failed or slow query, so password hashes and tokens never reach a webhook.
  • A log line that cannot be written is dropped. clog printed the write error to stdout, which serv and hooks cannot do because stdout carries the Git protocol.
  • Errors before the configuration is loaded go to stderr, and serv and hooks never write logs to stdout. Everything else on the console stays on stdout. The Windows service script now captures stderr too.
  • [log.xorm] and [log.gorm] produce the usual invalid option warning.
  • A scope is a component field instead of part of the message. Text sinks render it as the old [name] prefix.

CodeQL reports clear-text logging in internal/context/auth.go and weak hashing in internal/cryptox/sha.go. Both are false positives that exist on main: CodeQL treats slog calls as logging calls but did not model clog, and the hashed "password" is an access token used as a basic auth password. This PR changes those lines only to pass the logger.

Link to the issue: n/a

Checklist

  • I agree to follow the Code of Conduct by submitting this pull request.
  • I have read and acknowledge the Contributing guide.
  • I have added test cases to cover the new code or have provided the test plan. (if applicable)
  • I have added an entry to CHANGELOG. (if applicable)

Test plan

  1. go test ./internal/conf/ covers level parsing (including Trace), [log] FORMAT with and without the production run mode, per-handler levels (a debug line stays out of an info console and lands in the file logger), JSON output with RFC 3339 timestamps, and a nested scope rendered as a [database.gorm] prefix in text and a component field in JSON. It also runs a child process that calls FatalContext against a slow Slack server and a LEVEL = Fatal console: both queued posts arrive, the fatal one is labelled fatal, and the console shows only the fatal line.
  2. go test ./internal/dbx/ covers the GORM logger's levels (a failed query is an error, a slow query is a warning, record not found stays at debug) and checks that a failed insert hides its values unless every query is logged.
  3. go vet ./..., golangci-lint run, and go test ./... pass.
  4. Start Gogs and exercise the handlers that receive the logger by injection: API repo creation, Git smart HTTP clone and push (hooks write to log/hooks/), LFS batch and basic download, and the /api/web pages. Trigger a 500 and confirm the error line has the request method and path.
  5. Start Gogs with MODE = console, file and confirm log/gogs.log receives the same lines as the console. With RUN_MODE = prod the output is JSON, and FORMAT = text (or GOGS_LOG_FORMAT=text) switches it back to text. In dev mode FORMAT = json switches it to JSON.
  6. Push over SSH and confirm the Git client does not print server logs. The lines land in log/hooks/.

AI usage

This pull request was written by Amp, using the logging setup in pgrok and git-lfs-server as the reference.

@unknwon
unknwon force-pushed the logging/charmlog-logx branch 3 times, most recently from ef6c5ef to 71fd6a6 Compare November 14, 2026 05:34
Comment thread internal/context/auth.go Dismissed
Comment thread internal/context/auth.go Dismissed
Comment thread internal/context/auth.go Dismissed
Comment thread internal/context/auth.go Dismissed
Comment thread internal/context/auth.go Dismissed
Logging now uses charm.land/log/v2 as the slog handler and
unknwon.dev/x/logx as the logger, matching pgrok and git-lfs-server.
Console, file, Slack, and Discord stay configurable, and database
logs go through the same logger instead of xorm.log and gorm.log.
Every entry point builds its logger and passes it down. Functions take
`context.Context` and `*logx.Logger` first, route handlers use
`c.Logger`, and macaron and flamego get the logger mapped for injection.
The `internal/applog` global is removed.

Methods whose signatures are fixed by xorm hooks or templates read the
logger stored on the database handle, falling back to a no-op logger
when the handle is nil.

Also documents the logger argument convention in AGENTS.md, and labels
trace lines `TRAC` in text output.
Drop the internal/logx wrapper. Loggers are *logx.Logger from
unknwon.dev/x/logx, as in git-lfs-server and pgrok, and every call is a
structured slog call such as `logger.Error("Failed to get user", "userID", id, "error", err)`.

Handler setup lives in internal/conf/logging.go with the rotating file
writer and the Slack and Discord handlers. Trace maps to the debug level.
LFS and Git HTTP loggers are scoped at the call site.
GORM and xorm now log through real logger implementations instead of
writer adapters, so each query is one line with sql, args, rows, elapsed,
and source attributes, and failed GORM queries are errors. Long xorm
arguments are truncated. Internal server errors log the request method and
path. Production timestamps are RFC 3339 with the time zone.
- Wrap AvatarLink in the template FuncMap, templates pass only the email.
- Reopen the log file after a failed rotation so logging resumes.
- Post Slack and Discord messages from a queue of BUFFER_LEN.
- Map LEVEL = Fatal to the error level that FatalContext logs at.
- Keep the console logger when the hook log file cannot be created.
- Drop log lines the file writer cannot write instead of buffering them.
- Recreate a missing log directory when reopening the log file.
- Treat a negative BUFFER_LEN as 0.
- Refuse to start when a Slack or Discord logger has no URL.
- Ignore duplicate entries in [log] MODE.
- Post queued Slack and Discord messages before FatalContext exits.
- Log errors that stop gogs web through the configured logger once it exists.
- Hide query values in failed and slow GORM query logs unless every query is
  logged, so they do not reach Slack or Discord.
- Write console logs to stdout like clog, except in serv and hooks.
- Label FatalContext records as fatal, so LEVEL = Fatal sinks get only them.
- Bound the fatal webhook flush even when the queue is full.
- Reset rotation counters once the log file is renamed.
- Show each sink's level in the startup log, name the failed admin command,
  and honor TTY_FORCE for console colors.
- Log every query only in the web server and serv. admin, backup and restore
  log failed and slow queries, which main wrote to xorm.log and gorm.log.
- Keep query values on the debug Query line, off the error and warning that
  Slack or Discord may receive.
- Log the enabled log modes through the configured logger, so production
  output stays JSON.
Covers the new admin, organization settings and user settings
handlers, and the participant mail and email activation changes
merged from main.
Covers the new issue, label, milestone, release, branch, wiki, editor,
commit, repository settings, webhook, Git hook, fork, new repository,
passkey and authentication source handlers, plus the remaining calls
merged into existing files.
@unknwon
unknwon force-pushed the logging/charmlog-logx branch from a2301ce to 606e744 Compare November 16, 2026 17:41
@unknwon
unknwon added this pull request to stack #8631 November 16, 2026 18:49
Bumps unknwon.dev/x so Scoped sets a dotted "component" attribute
instead of prefixing the message. Text sinks and webhooks still show it
as a "[gorm] " prefix, while JSON keeps it as a field that log
explorers can filter on.
Trace stays accepted as the same level as Debug.
FORMAT is "text" or "json", and empty keeps JSON for production only.
The default config reads it from GOGS_LOG_FORMAT, which both Docker
images set to "json".
The run mode no longer switches the output to JSON. FORMAT defaults to
text, and the Docker images set it to JSON.
Empty is JSON in production and text otherwise, and "text" or "json"
overrides it, e.g., to keep text logs in production.
@unknwon
unknwon merged commit 6c449ce into main Nov 16, 2026
17 checks passed
@unknwon
unknwon deleted the logging/charmlog-logx branch November 16, 2026 19:30
unknwon added a commit that referenced this pull request Nov 16, 2026
#8630 merged while #8529 was open, so main does not build.
unknwon added a commit that referenced this pull request Nov 16, 2026
The code browser handlers from #8630 still called the clog package that
#8529 removed, so main did not build.
mvanhorn added a commit to mvanhorn/gogs that referenced this pull request Nov 17, 2026
Resolve the conflict in cmd/gogs/restore.go: keep the custom/data hold,
moveTree and rollback steps from this branch, and switch their fatal
logging to the logger.FatalContext style that main adopted in gogs#8529.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants