Cysharp / ZLogger

Zero Allocation Text/Structured Logger for .NET with StringInterpolation and Source Generator, built on top of a Microsoft.Extensions.Logging.
MIT License
1.16k stars 81 forks source link

Format DateTime with custom format? #9

Closed theolivenbaum closed 4 years ago

theolivenbaum commented 4 years ago

Hi @neuecc , awesome work on the library!

Just posting this here as something I noticed that is missing on the library... It seems like the formatter doesn't support DateTime formatting, like this for the PrefixFormatter:

logging.AddZLoggerConsole(options => options.PrefixFormatter = (buf, info) => ZString.Utf8Format(buf, "[{0}] [{1:hh:mm:ss}]", info.LogLevel, info.Timestamp.LocalDateTime));

This works for now of course, but it doesn't add the leading 0 on the numbers:

logging.AddZLoggerConsole(options => options.PrefixFormatter = (buf, info) => ZString.Utf8Format(buf, "[{0}] [{1}:{2}:{3}]", GetLogLevelString(info.LogLevel), info.Timestamp.LocalDateTime.Hour, info.Timestamp.LocalDateTime.Minute, info.Timestamp.LocalDateTime.Second));
richard-green commented 4 years ago

I believe this limitation comes from ZString.Utf8Format, specifically the StandardFormat.Parse function:

var writeFormat = StandardFormat.Parse(indexParse.FormatString); // exception here

neuecc commented 4 years ago

Yes, it is StandardFormat's limitation. I already requested to dotnet/runtime. https://github.com/dotnet/runtime/issues/28942

I'm hoping to improve it too, so please Up Vote.

theolivenbaum commented 4 years ago

Thanks @neuecc, will follow the issue there - meanwhile the [{1}:{2}:{3}] works fine for now, so feel free to close this issue if you want!

neuecc commented 4 years ago

@theolivenbaum

it doesn't add the leading 0 on the numbers:

StandardFormatter supports precision and it can use like {0:D2}. I'll write to document.