All of lore.kernel.org
 help / color / mirror / Atom feed
From: Eric Blake <eblake@redhat.com>
To: "Daniel P. Berrangé" <berrange@redhat.com>
Cc: qemu-devel@nongnu.org, "Markus Armbruster" <armbru@redhat.com>,
	"Dr. David Alan Gilbert" <dave@treblig.org>,
	"Marc-André Lureau" <marcandre.lureau@redhat.com>,
	"Paolo Bonzini" <pbonzini@redhat.com>,
	"Peter Maydell" <peter.maydell@linaro.org>,
	"Richard Henderson" <richard.henderson@linaro.org>
Subject: Re: [PATCH 3/6] util: introduce a configurable message format template
Date: Thu, 3 Dec 2026 15:44:08 -0600	[thread overview]
Message-ID: <axHWdEu4fnbvJqsu@redhat.com> (raw)
In-Reply-To: <20261203172543.676434-4-berrange@redhat.com>

On Thu, Dec 03, 2026 at 05:25:40PM +0000, Daniel P. Berrangé wrote:
> Currently error messages, generic log messages and chardev logs
> can all have a timestamp prepended, by using the '-msg' argument's
> 'timestamp' flag.
> 
> There are various extra bits of information that are interesting
> to emit in various scenarios. Rather than adding many more flags
> to '-msg' and hardcoding the order they are emitted in, this
> introcuces a configuraable message format template.

introduces, configurable

> 
> A format string template is a concatenation of the following
> components
> 
>   * literal string:
> 
>       text
> 
>     In the literal text, a '\' must be used to escape any '{',
>     '}' or '\' characters.
> 
>   * a variable substition:
> 
>       {variablename}
> 
>     where variable name is one of:
> 
>      - 'timestamp': the ISO 8601 formatted current time
>      - 'progname': the current program name
>      - 'thread': the current thread name
>      - 'tid': the thread ID
>      - 'pid': the process ID
>      - 'location': the current input location

Missing mention of 'guestname', 'level', and 'levelalt' from the
implementation [1]. Maybe it is sufficient to have the commit message
point to the .h file and maybe just summarize things with a subset,
rather than trying to duplicate the list in two places then ending up
inconsistent.

> 
>   * an conditional expression

s/an /a /

> 
>       {?{variablename}formatstring}
>       {!{variablename}formatstring}
> 
>     which evaluates whether the variable is non-empty or empty
>     respectively, and processes the nested format string.
> 
> As example:
> 
>   "Demo {pid}{?{progname} (in program '}{progname}{?{progname}')}"
> 
> Given a 'pid' value of '123' will print the following
> if progname is empty:
> 
>    "Demo 123"
> 
> or, if the program name is the strnig 'qemu', will print:

string

> 
>    "Demo text (in program 'qemu')"

s/text/123/ to match the earlier explanation.

> 
> Signed-off-by: Daniel P. Berrangé <berrange@redhat.com>
> ---
> +++ b/include/qemu/message-format.h
> @@ -0,0 +1,97 @@
...
> + * In either the literal text, or the prefix and suffix
> + * of a conditional placeholder, '\' can be used to
> + * escape the special meaning of '{', '}' and '\'.
> + *
> + * As example:
> + *
> + *   "Demo {pid}{? (in program '{progname}')}"
> + *
> + * Given a 'pid' value of '123' will print
> + *
> + *    "Demo 123"
> + *
> + * or, if the program name is available, will print:
> + *
> + *    "Demo text (in program 'qemu')"

s/text/123/

> + *
> + * Currently defined placeholders are:
> + *
> + *  - 'timestamp': the ISO 8601 formatted current time
> + *  - 'progname': the current program name
> + *  - 'thread': the current thread name
> + *  - 'tid': the thread ID
> + *  - 'pid': the process ID
> + *  - 'location': the current input location
> + *  - 'guestname': the current guest name
> + *  - 'level': the message level (debug, info, warning, error)
> + *  - 'levelalt': as 'level' but no string printed for 'error'
> + *                or 'debug'

[1] see comment above about commit message.

> + *
> + * Returns: a new message format, or NULL on error
> + */
> +QMessageFormat *qmessage_format_new_from_string(const char *formatstr,
> +                                                Error **errp);
...

> +++ b/tests/unit/test-util-message-format.c
> @@ -0,0 +1,226 @@
> +/* SPDX-License-Identifier: GPL-2.0-or-later */
> +
> +#include "qemu/osdep.h"
> +#include "qemu/message-format.h"
> +#include "qemu/location.h"
> +#include "qemu/error-report.h"
> +
> +
> +/*
> + * functions we "mock" override to give predictable
> + * output for testing
> + */
> +GDateTime *g_date_time_new_now_utc(void)
> +{
> +    return g_date_time_new_from_unix_utc(872835240);

Anything special about that date in 1997? :)

> +static void test_util_message_format_escapes(void)
> +{
> +    g_autoptr(GString) str = g_string_new(NULL);
> +    g_autoptr(QMessageFormat) format =
> +        qmessage_format_new_from_string(
> +            "Test: {progname}{?{progname}\\\\\\}\\\\}!", &error_abort);

Leaning toothpicks! But literal \ in error strings is rare enough that
I don't mind this choice of escape.

> +
> +static void test_util_message_format_everything(void)
> +{
> +    g_autoptr(GString) str = g_string_new(NULL);
> +    g_autoptr(QMessageFormat) format =
> +        qmessage_format_new_from_string(
> +            "{timestamp}: [{level}] {progname}:"
> +            "{location}({pid}:[{thread}:{tid}]): {guestname}: OK",
> +            &error_abort);

Misses {levelalt}. But I'm liking the flexibility.

test_util_message_format_bad() covers incomplete strings, like
"{timestamp" (no terminating "}"); but should it also cover the case of
an unrecognized variable, such as "{bogus}"?

> +++ b/util/message-format.c
> @@ -0,0 +1,449 @@

> +
> +static char *qmessage_format_unescape_text(const char *text,
> +                                           size_t textlen)
> +{
> +    size_t i, n;
> +    bool escape = false;
> +    char *rawtext = g_new0(char, textlen + 1);
> +    for (i = 0, n = 0; i < textlen; i++) {
> +        if (escape || text[i] != '\\') {
> +            rawtext[n++] = text[i];
> +            escape = false;
> +        } else {
> +            escape = true;
> +        }
> +    }

Technically, this means \ escapes any character, not just \,{,} as
documented. If we want to add other escape sequences later (unlikely?)
then being noisy on unknown escape sequences now would make later
additions less likely to change behavior if they are accidentally
used; but costs more validation effort.  I'm inclined to leave it the
way you have it.

> +static const char *
> +qmessage_format_end_of_literal(const char *formatstr,
> +                               const char *tmp,
> +                               char terminator,
> +                               Error **errp)
> +{
> +    bool escape = false;
> +    while (1) {
> +        if (escape) {
> +            if (*tmp == '\0') {
> +                error_setg(errp,
> +                           "Unterminated escape at and of format string '%s'",

s/and/end/

> +                           formatstr);
> +                return NULL;
> +            } else if (*tmp != '\\' && *tmp != '{' && *tmp != '}') {
> +                error_setg(errp,
> +                           "Unrecognised escape char '\\%c' in string '%s'",
> +                           *tmp, formatstr);
> +                return NULL;
> +            }
> +            escape = false;

While here, you are checking for known escapes.

> +        } else {
> +            switch (*tmp) {
> +            case '\\':
> +                escape = true;
> +                break;
> +            case '{':
> +            case '}':
> +            case '\0':
> +                return tmp;
> +            }
> +        }
> +        tmp++;
> +    }
> +    g_assert_not_reached();
> +}
> +
> +
> +static QMessageFormat *
> +qmessage_format_new_internal(const char *formatstr,
> +                             const char **tmpptr,
> +                             char terminator,
> +                             Error **errp)
> +{
> +    g_autoptr(QMessageFormat) format = g_new0(QMessageFormat, 1);
> +    const char *tmp = *tmpptr;
> +
> +    /*
> +     * We're parsing 'formatstr' which can be a concatenation
> +     * of any of the following
> +     *
> +     * a. literal text:
> +     *
> +     *  text
> +     *
> +     * b. variable subsitution

substitution

> +     *
> +     *  {variable}
> +     *
> +     * c. expression with literal text
> +     *
> +     *  {?{variable}formatstr}
> +     *  {!{variable}formatstr}
> +     *
> +     * Literal 'text' can use '\' to escape '{', '}' or '\'
> +     */
> +
> +void qmessage_format_emit(QMessageFormat *format,
> +                          QMessageLevel level,
> +                          QMessageWriteFunc writefn,
> +                          void *opaque)
> +{
> +    size_t i;
> +
> +#define WRITE(str) \
> +    writefn(opaque, str, strlen(str))

Looks funny to define this...

> +
> +    for (i = 0; i < format->nfields; i++) {
> +        QMessageFormatField *field = &(format->fields[i]);
> +        bool empty = false;
> +
> +        switch (field->type) {
> +        case QMESSAGE_FORMAT_TYPE_LITERAL:
> +            writefn(opaque, field->data.literal,
> +                    strlen(field->data.literal));

...and then not use it as WRITE(field->data.literal);

-- 
Eric Blake, Principal Software Engineer
Red Hat, Inc.
Virtualization:  qemu.org | libguestfs.org



  reply	other threads:[~2026-12-03 21:44 UTC|newest]

Thread overview: 16+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-03 17:25 [PATCH 0/6] util: configurable / flexible error/log message output format Daniel P. Berrangé
2026-12-03 17:25 ` [PATCH 1/6] util: pull Location struct and APIs into location.{c,h} Daniel P. Berrangé
2026-12-03 20:51   ` Eric Blake
2026-12-03 17:25 ` [PATCH 2/6] util: add helper to query if a location is set Daniel P. Berrangé
2026-12-03 20:51   ` Eric Blake
2026-12-03 17:25 ` [PATCH 3/6] util: introduce a configurable message format template Daniel P. Berrangé
2026-12-03 21:44   ` Eric Blake [this message]
2026-12-04  9:22     ` Daniel P. Berrangé
2026-12-04  0:32   ` Dr. David Alan Gilbert
2026-12-03 17:25 ` [PATCH 4/6] util: convert log code to support QMessageFormat Daniel P. Berrangé
2026-12-03 21:52   ` Eric Blake
2026-12-03 17:25 ` [PATCH 5/6] util: convert error report code to use QMessageFormat Daniel P. Berrangé
2026-12-03 21:55   ` Eric Blake
2026-12-03 17:25 ` [PATCH 6/6] util: add '-msg format=FORMATSTR' argument Daniel P. Berrangé
2026-12-03 22:02   ` Eric Blake
2026-12-04  9:23     ` Daniel P. Berrangé

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=axHWdEu4fnbvJqsu@redhat.com \
    --to=eblake@redhat.com \
    --cc=armbru@redhat.com \
    --cc=berrange@redhat.com \
    --cc=dave@treblig.org \
    --cc=marcandre.lureau@redhat.com \
    --cc=pbonzini@redhat.com \
    --cc=peter.maydell@linaro.org \
    --cc=qemu-devel@nongnu.org \
    --cc=richard.henderson@linaro.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.