json-util: fine tune json_dispatch_log_level()

Let's give the user control on how to handle JSON "null" assignments of
the log level. As one of three cases: as failure, as LOG_NULL (i.e. to
turn off logging) or as LOG_INFO (as our usual default log level).

Let's then use that in the generic SetLogLevel() call, so that callers
can use it to explicitly turn off logging in a service.

Note that this was (probably accidentally) already implemented, except
that the introspection enforcement blocked it. Let's clean this up and
make this officially a thing, since it's generally useful to turn off
logging I think.
This commit is contained in:
Lennart Poettering
2025-01-18 23:24:29 +01:00
parent a153d7cbd2
commit fa3137f9d0
3 changed files with 14 additions and 5 deletions
+11 -3
View File
@@ -344,8 +344,15 @@ int json_dispatch_ifindex(const char *name, sd_json_variant *variant, sd_json_di
int json_dispatch_log_level(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
int *log_level = ASSERT_PTR(userdata), r, t;
/* If SD_JSON_STRICT is set, we'll refuse attempts to set the log level to null. If SD_JSON_RELAX is
* set we'll turn null (and any negative log level) into LOG_NULL (which when used as max log level
* means: no logging). Otherwise we turn null into LOG_INFO (which is typically our default). */
if (sd_json_variant_is_null(variant)) {
*log_level = -1;
if (FLAGS_SET(flags, SD_JSON_STRICT))
return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' may not be null.", strna(name));
*log_level = FLAGS_SET(flags, SD_JSON_RELAX) ? LOG_NULL : LOG_INFO;
return 0;
}
@@ -353,8 +360,9 @@ int json_dispatch_log_level(const char *name, sd_json_variant *variant, sd_json_
if (r < 0)
return r;
/* If SD_JSON_RELAX is set allow a zero interface index, otherwise refuse. */
if (LOG_PRI(t) != t)
if (FLAGS_SET(flags, SD_JSON_RELAX) && t < 0)
t = LOG_NULL;
else if (LOG_PRI(t) != t)
return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a valid log level.", strna(name));
*log_level = t;