【问题标题】:How can I set the culture for dotnet logging?如何设置 dotnet 日志记录的文化?
【发布时间】:2020-08-26 15:02:42
【问题描述】:

我正在使用 dotnetcore 3.1 登录。当我在记录器中使用复合格式的日期时,我得到的格式与我在应用程序代码中将日期转换为字符串时不同。

这段代码:

ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
_logger = loggerFactory.CreateLogger<Program>();
_logger.LogInformation("TEST date via format string {}", DateTime.Today);
_logger.LogInformation("TEST date with concatentation:" + DateTime.Today);

产生这个输出(注意日月顺序的变化):

TEST date via format string 08/26/2020 00:00:00
TEST date with concatentation:26/08/2020 00:00:00

我很惊讶记录器没有从应用程序继承文化。我是否遗漏了什么,如果没有,我该如何控制记录器的文化?

【问题讨论】:

    标签: c# logging .net-core culture .net-core-3.0


    【解决方案1】:

    这让我很感兴趣,我决定深入研究一下。

    通过Logging repository中的dotnet LogValuesFormatter判断,在使用大括号{}时,Format方法的调用使用了不变的文化。

    其中,根据Microsoft docs设置为MM/dd/yyyy。

    但是,连接似乎使用了当前区域性。

    我建议,如果您想使用大括号格式,您只需调用 ToString 并添加文化,以便在格式化程序获取日期之前将日期转换为当前文化中的字符串。您还可以使用字符串插值,它使用与大括号类似的语法,但似乎也使用当前文化:

    _logger.LogInformation("Current culture is "+  CultureInfo.CurrentCulture.Name);
    _logger.LogInformation("TEST date via format string {}", DateTime.Today);
    _logger.LogInformation("TEST date via cultured format string {}", DateTime.Today.ToString(CultureInfo.CurrentCulture));
    _logger.LogInformation("TEST date with concatentation:" + DateTime.Today);
    _logger.LogInformation($"TEST date with string interpolation: {DateTime.Today}");
    

    这段代码给了我这个输出:

    Current culture is en-GB
    TEST date via format string 09/12/2020 00:00:00
    TEST date via cultured format string 12/09/2020 00:00:00
    TEST date with concatentation:12/09/2020 00:00:00
    TEST date with string interpolation: 12/09/2020 00:00:00
    

    【讨论】:

    • 链接的源代码说明我的问题的答案是“不。我无法控制记录器的文化”。虽然我对 MS 强制执行 InvariantCulture 的决定感到矛盾,但对于该日期格式的 MM/dd/yyyy 选择是令人反感的:) btw @reisclef 检查您的第二个链接,它与第一个链接相同。谢谢!
    • 完全同意你@TrevorJ 的说法。并感谢您指出链接错误。这就是我在深夜回答问题时得到的!我现在已经更正了。 :)
    猜你喜欢
    • 2021-11-06
    • 2012-09-24
    • 2012-09-03
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多