opentelemetry-go-contrib
opentelemetry-go-contrib copied to clipboard
Logger support in otelhttp
Problem Statement
The otelhttp middleware is an ideal place to log HTTP transactions, because important data are available, such as:
- HTTP status code
- Elapsed Time
- Bytes read and written
Now that the minimal Go version is 1.21, in which the package log/slog is part of the standard library,
a standard API is available to generate structured log records.
OpenTelemetry loggers can be used with the log/slog API via go.opentelemetry.io/contrib/bridges/otelslog.
Proposed Solution
The middleware can optionally be configured with a *slog.Logger:
mware := otelhttp.NewMiddleware(operation, otelhttp.WithLogger(logger))
If a Logger has been configured, a log record will be emitted with the same attributes as the Span:
{
"time": "2024-04-05T15:42:16.926178547-07:00",
"level": "INFO",
"msg": "operation",
"http.method": "GET",
"http.scheme": "http",
"net.host.name": "tonio.attlocal.net",
"net.host.port": 8080,
"net.protocol.name": "http",
"net.protocol.version": "1.1",
"http.status_code": 200,
"http.wrote_bytes": 3954,
"http.server.duration": 4.426442,
}
Alternatives
Middlewares already exist to generate access logs from HTTP servers based onnet/http and similar routers,
such as https://pkg.go.dev/github.com/gorilla/handlers?utm_source=godoc#LoggingHandler . The drawbacks are that:
- It is wasteful to have more than one
httpsnoopin your middleware stack (and perhaps dangerous?) - The middlewares i have found cannot be configured with a
slog.Logger.
Prior Art
N/A
Additional Context
N/A
Please open an issue with the OTel semantic conventions: https://github.com/open-telemetry/semantic-conventions
We do not plan to add logging to the canonical library without a standardization across OpenTelemetry.