JsonConsoleFormatter throws on NaN and infinite double and float values, failing the log call

Abierto Apto para principiantes
#138,418 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@Mohamedadel-prog ya está trabajando en esto.

Desde el 28/11/2026.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
82/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
csharp, json

Línea de trabajo

Empieza en JsonConsoleFormatter.WriteItem, donde el issue identifica llamadas incondicionales a Utf8JsonWriter.WriteNumber con double y float. Revisa las pruebas del formateador para state, scopes y atributos de registros almacenados en búfer; después, ejecuta las pruebas pertinentes. Se considera terminado cuando NaN y el infinito positivo y negativo se escriben como cadenas invariantes y las llamadas de registro se completan sin lanzar excepciones.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

area-Extensions-Logging untriaged
Description

JsonConsoleFormatter writes a double or float value of an entry's state, of a scope, or of a buffered record's attributes with Utf8JsonWriter.WriteNumber, which refuses NaN, positive infinity and negative infinity. The ArgumentException leaves the formatter, so the log call itself throws an AggregateException and no line is written. With IncludeScopes, a scope holding such a value makes every log call inside it throw. The same calls through the simple formatter write their messages.

A log call should not fail because of a value's content: on a service that logs rates or prices, a NaN is an ordinary value to log.

Reproduction Steps
// Microsoft.Extensions.Logging.Console 11.0.0
using Microsoft.Extensions.Logging;

using var loggerFactory = LoggerFactory.Create(builder => builder.AddJsonConsole(options => options.IncludeScopes = true));
var logger = loggerFactory.CreateLogger("Repro");

logger.LogInformation("Rate {Rate}", double.NaN); // throws

using (logger.BeginScope("Rate {Rate}", double.PositiveInfinity))
{
    logger.LogInformation("Inside a scope"); // throws
}
Expected behavior

The entry is written. NaN and the infinities could be written as the strings "NaN", "Infinity" and "-Infinity", as System.Text.Json writes them under JsonNumberHandling.AllowNamedFloatingPointLiterals, which the exception text itself suggests, the way the formatter already writes a value of any type it has no case for as a string.

Actual behavior
System.AggregateException: An error occurred while writing to logger(s). (.NET number values such as positive and negative infinity cannot be written as valid JSON. To make it work when using 'JsonSerializer', consider specifying 'JsonNumberHandling.AllowNamedFloatingPointLiterals' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling).)
 ---> System.ArgumentException: .NET number values such as positive and negative infinity cannot be written as valid JSON. To make it work when using 'JsonSerializer', consider specifying 'JsonNumberHandling.AllowNamedFloatingPointLiterals' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling).
   at System.Text.Json.ThrowHelper.ThrowArgumentException_ValueNotSupported()
   at System.Text.Json.Utf8JsonWriter.WriteNumber(ReadOnlySpan`1 propertyName, Double value)
   at System.Text.Json.Utf8JsonWriter.WriteNumber(String propertyName, Double value)
   at Microsoft.Extensions.Logging.Console.JsonConsoleFormatter.WriteItem(Utf8JsonWriter writer, KeyValuePair`2 item)
   at Microsoft.Extensions.Logging.Console.JsonConsoleFormatter.WriteInternal(IExternalScopeProvider scopeProvider, TextWriter textWriter, String message, LogLevel logLevel, String category, Int32 eventId, String exception, Boolean hasState, String stateMessage, IReadOnlyList`1 stateProperties, DateTimeOffset stamp)
   at Microsoft.Extensions.Logging.Console.JsonConsoleFormatter.Write[TState](LogEntry`1& logEntry, IExternalScopeProvider scopeProvider, TextWriter textWriter)
   at Microsoft.Extensions.Logging.Console.ConsoleLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
   --- End of inner exception stack trace ---
   at Microsoft.Extensions.Logging.Logger.ThrowLoggingError(List`1 exceptions)

JsonWriterOptions.SkipValidation = true does not change it, and a float throws the same way.

Regression?

No: Microsoft.Extensions.Logging.Console 10.0.0 throws the same way.

Known Workarounds

A ConsoleFormatter of one's own that presents the state, the scopes and a buffered record's attributes with such values as strings, then hands the entry to the JSON formatter.

Configuration

.NET 11.0 (SDK 11.0.100), Microsoft.Extensions.Logging.Console 11.0.0 and 10.0.0, Windows 11 x64. WriteItem has no platform-specific code.

Other information

WriteItem has a case double and a case float that call writer.WriteNumber unconditionally; a check with double.IsFinite / float.IsFinite there, writing the invariant string otherwise, would fix it for state, scopes and buffered records at once.

Lenguaje dominante
C#
Estrellas
18.5k
Forks
5.8k
Merge medio
2 d 8 h
PR fusionados (30 d)
597

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de dotnet/runtime

Todos los issues de dotnet/runtime

Issues similares

Más issues de C#

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.