-
Couldn't load subscription status.
- Fork 693
Description
Problem Statement
I would like to easily convert a string like "info", "DEBUG", "error3", or "FATAL4" to either minsev.Severity or minsev.SeverityVar.
The use case here is reading log severity from an environment variable. It is common for log severity to differ by environment, meaning that it is reasonable to expect the value of log severity to be read from an environment variable. However, there is currently no easy way to convert a string to minsev.Severity or minsev.SeverityVar. Such conversion would have to be done manually.
Proposed Solution
I would like minsev.Severity to implement:
- encoding.TextUnmarshaler.
- encoding.TextMarshaler
- encoding/json.Marshaler
- encoding/json.Unmarshaler
- encoding.TextAppender
- fmt.Stringer
and minsev.SeverityVar to implement:
We should have Severity and SeverityVar implement the fmt.Stringer interface so that printing a Severity or SeverityVar results in an output of, for example, FATAL2 instead of 13.
See the Prior Art section. I am used to using slog, but this problem statement does not apply to slog because slog.Level and slog.LevelVar both implement encoding.TextUnmarshaler.
Alternatives
One alternative would be to implement such conversion from a string to minsev.Severity or minsev.SeverityVar myself. However, I consider this to be a fairly common use case.
Prior Art
The standard library slog package has types that are analogous to the minsev package. Namely:
- slog.Leveler is analogous to minsev.Severitier
- slog.Level is analogous to minsev.Severity
- slog.LevelVar is analogous to minsev.SeverityVar
slog.Level implements
- encoding.TextUnmarshaler
- encoding.TextMarshaler
- encoding/json.Marshaler
- encoding/json.Unmarshaler
- encoding.TextAppender
- fmt.Stringer
slog.LevelVar implements
I imagine the implementation in the minsev package would be very similar to those in the slog package.
Additional Context
There are libraries that can parse environment variables into a struct, like ardanlabs/conf. This works with slog, but not with minsev because of the above.