Skip to content

[Analyzer] Usage of ToString in logging source generator method call sites #78402

@stephentoub

Description

@stephentoub

We should consider an analyzer that flags use of ToString() in call sites to logging methods and suggests reconsidering the shape of the logging method such that it takes a strongly-typed value. In many situations, logging is disabled or set at a log level that will result in a particular event being disabled, and doing the ToString() at the call site is then often unnecessary allocation / expense. For example, given:

[LoggerMessage(EventId = 0, Level = LogLevel.Information, Message = "Excessively large timeout `{timeout}`")]
public static partial void ExcessivelyLargeTimeout(this ILogger logger, string timeout);
...
TimeSpan timeout = ...;
logger.ExcessivelyLargeTimeout(timeout.ToString());

the analyzer would flag the .ToString() and suggest the ExcessivelyLargeTimeout method should be changed to take a TimeSpan instead of a string, with the .ToString() removed from the call site.

Performance rules Category
Severity = suggestion

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-Extensions-Loggingcode-analyzerMarks an issue that suggests a Roslyn analyzerhelp wanted[up-for-grabs] Good issue for external contributorsin-prThere is an active PR which will close this issue when it is mergedpartner-impactThis issue impacts a partner who needs to be kept updated

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions