Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the culture for dotnet logging?

I'm using logging in dotnetcore 3.1. When I use composite formatting of dates in a logger, I get a different format than if I convert the date to a string in my application code.

This code:

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);

produces this output (note the change in order of days and months):

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

I'm surprised the logger doesn't inherit the culture from the application. Am I missing something, and if not how can I control the culture of the logger?

like image 649
TrevorJ Avatar asked Oct 12 '25 11:10

TrevorJ


1 Answers

This interested me, and I decided to dig around a bit.

Judging by the dotnet LogValuesFormatter in the Logging repository, when using the braces { }, the call to the Format method uses the invariant culture.

Which, according to the Microsoft docs is set up as MM/dd/yyyy.

However, the concatenation does appear to use the current culture.

I would suggest that if you want to use the braces formatting that you simply call ToString and add the culture in order to cast the date to a string in the current culture, before the formatter gets a hold of it. You could also use string interpolation which uses a similar syntax to the braces, but appears to also use the current culture:

_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}");

This code gives me this output:

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
like image 115
Reisclef Avatar answered Oct 14 '25 02:10

Reisclef