如何设置dotnet记录的区域性?

问题描述

我正在使用登录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

我很惊讶记录器未从应用程序继承文化。我是否缺少某些东西,如果没有,我该如何控制记录仪的文化?

解决方法

这引起了我的兴趣,我决定深入研究。

根据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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...