This product is not supported for your selected Datadog site. ().

Metadata

ID: csharp-security/logging-exception

Language: C#

Severity: Info

Category: Best Practices

Description

This rule discourages logging only the exception message without including the full exception object. Logging just the exception message can omit valuable context, such as the stack trace, which is essential for diagnosing and troubleshooting issues effectively.

To comply with this rule, always pass the exception object as a parameter to your logging method instead of concatenating or interpolating the exception message into the log string. For example, use logger.error("Error processing file", e); rather than logger.error($"Error: {e.Message}");. This practice ensures that the logging framework captures the full exception details, including stack traces and inner exceptions.

Note that you may still want to log the full exception of part of its attribute. In this case, you can disable this rule for your repository or organization.

Non-Compliant Code Examples

try {
    processFile();
} catch (IOException ex) {
    logger.error($"Error: {ex.Message}");
}
try {
    processFile();
} catch (IOException e) {
    logger.error("Error processing file: " + e.getMessage());
}

Compliant Code Examples

try {
    processFile();
} catch (IOException e) {
    logger.error("Error processing file", e);
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security