Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unicode characters are escaped when using JSON formatter #184

Open
AlanLiu90 opened this issue Nov 15, 2024 · 0 comments · May be fixed by #185
Open

Unicode characters are escaped when using JSON formatter #184

AlanLiu90 opened this issue Nov 15, 2024 · 0 comments · May be fixed by #185

Comments

@AlanLiu90
Copy link

AlanLiu90 commented Nov 15, 2024

The following program outputs:

{"Message":"\u3084\u304D","tako":"\u305F\u3053","yaki":"\u3084\u304D"}
using System;
using System.IO;
using System.Text;
using Microsoft.Extensions.Logging;
using ZLogger;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using var ms = new MemoryStream();

            using var loggerFactory = LoggerFactory.Create(logging =>
            {
                logging.SetMinimumLevel(LogLevel.Debug);

                logging.AddZLoggerStream(ms, options =>
                {
                    options.IncludeScopes = true;

                    options.UseJsonFormatter(formatter =>
                    {
                        formatter.IncludeProperties = IncludeProperties.Message |
                            IncludeProperties.ScopeKeyValues | IncludeProperties.ParameterKeyValues;
                    });
                });
            });

            var logger = loggerFactory.CreateLogger("test");

            using var scope = logger.BeginScope("{tako}", "たこ");

            var yaki = "やき";
            logger.ZLogDebug($"{yaki}");

            loggerFactory.Dispose();

            using var sr = new StreamReader(new MemoryStream(ms.ToArray()), Encoding.UTF8);
            var json = sr.ReadLine();

            Console.WriteLine(json);
        }
    }
}

Looking into the source code, SystemTextJsonZLoggerFormatter sets JsonSerializerOptions to avoid escaping all unicode characters, but it doesn't work.

It seems the setting should be applied to Utf8JsonWriter directly. I tried to change the code to:

jsonWriter ??= new Utf8JsonWriter(writer, new JsonWriterOptions
{
    Encoder = JsonSerializerOptions.Encoder
});

Then it can output correctly:

{"Message":"やき","tako":"たこ","yaki":"やき"}
@AlanLiu90 AlanLiu90 linked a pull request Nov 15, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant