---
title: Avoid logging credentials and personal data
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Avoid logging credentials and personal data
---

> For the complete documentation index, see [llms.txt](https://docs.datadoghq.com/llms.txt).

# Avoid logging credentials and personal data

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com, us2.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ({% placeholder "user-datadog-site-name" /%}).
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `csharp-security/ensure-secure-logging`

**Language:** C#

**Severity:** Notice

**Category:** Security

**CWE**: [532](https://cwe.mitre.org/data/definitions/532.html)

## Description{% #description %}

Logging credentials or personal data exposes them to anyone who can read the logs.

This rule flags logging calls (Microsoft.Extensions.Logging, Serilog, NLog, log4net) where an argument's name is a known sensitive name, such as `password`, `secret`, `apiKey`, `accessToken`, `connectionString`, `username`, `email`, or `ssn`. Names are matched case-insensitively, ignoring a leading underscore. Values derived from them, like `password.Length`, are not flagged.

Remove the sensitive value from the log message, or mask it first.

#### Learn More{% #learn-more %}

- [CWE-532: Insertion of Sensitive Information into Log File](https://cwe.mitre.org/data/definitions/532)

## Non-Compliant Code Examples{% #non-compliant-code-examples %}

```csharp
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

public class AccountController : Controller
{
    private readonly ILogger<AccountController> _logger;

    public AccountController(ILogger<AccountController> logger)
    {
        _logger = logger;
    }

    [HttpPost]
    public IActionResult Login(string username, string password)
    {
        _logger.LogInformation("User {username} attempting to log in", username);

        // authentication logic...
        return Ok();
    }
}
```

```csharp
using System.Web;
using System.Web.Mvc;
using NLog;

public class UserController : Controller
{
    private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
    
    [HttpPost]
    public ActionResult Register(string username)
    {
        if (!string.IsNullOrEmpty(username))
        {
            _logger.Warn("Registration attempt for user: " + username); // Noncompliant
        }
        return View();
    }
}

void main() {}
```

```csharp
using System;
using Microsoft.Extensions.Logging;
using NLog;
using Serilog;

public class AccountController : Controller
{
    private readonly ILogger<AccountController> _logger;
    private readonly string _apiKey;
    private string _accessToken;
    private static readonly NLog.Logger _nlog = LogManager.GetCurrentClassLogger();
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(AccountController));

    public AccountController(ILogger<AccountController> logger, string s)
    {
        _logger = logger;
        _logger.LogInformation("Secret {s}", secret); // Noncompliant: constructor parameter
    }

    // Microsoft.Extensions.Logging levels
    public void Levels(string password)
    {
        _logger.Log(LogLevel.Warning, "Pwd {p}", password); // Noncompliant
        _logger.LogTrace("Pwd {p}", password); // Noncompliant
        _logger.LogDebug("Pwd {p}", password); // Noncompliant
        _logger.LogInformation("Pwd {p}", password); // Noncompliant
        _logger.LogWarning("Pwd {p}", password); // Noncompliant
        _logger.LogError("Pwd {p}", password); // Noncompliant
        _logger.LogCritical("Pwd {p}", password); // Noncompliant
    }

    // Serilog, NLog and log4net
    public void OtherLibraries(string accessToken, string clientSecret)
    {
        Log.Information("Token {t}", accessToken); // Noncompliant
        Log.Warning("Token {t}", accessToken); // Noncompliant
        Log.Fatal("Token {t}", accessToken); // Noncompliant
        _nlog.Info("Secret " + clientSecret); // Noncompliant
        log.Error("Secret " + clientSecret); // Noncompliant
    }

    // Where the value comes from
    public void Sources(User user, string accessToken = null)
    {
        var password = GetPassword();
        _logger.LogInformation("Pwd {p}", password); // Noncompliant: local variable
        _logger.LogInformation("Key {k}", _apiKey); // Noncompliant: field
        _logger.LogInformation("Pwd {p}", user.Password); // Noncompliant: property
        _logger.LogInformation("Token {t}", accessToken); // Noncompliant: parameter with default value
    }

    // Name variants: case-insensitive, leading underscore ignored
    public void Names(string ApiKey, string connectionString, string ssn, string creditCardNumber,
                      User user, string phoneNumber, string FirstName, string pwd)
    {
        _logger.LogInformation("{v}", ApiKey); // Noncompliant
        _logger.LogInformation("{v}", _accessToken); // Noncompliant
        _logger.LogInformation("{v}", connectionString); // Noncompliant
        _logger.LogInformation("{v}", ssn); // Noncompliant
        _logger.LogInformation("{v}", creditCardNumber); // Noncompliant
        _logger.LogInformation("{v}", user.Email); // Noncompliant
        _logger.LogInformation("{v}", phoneNumber); // Noncompliant
        _logger.LogInformation("{v}", FirstName); // Noncompliant
        _logger.LogInformation("{v}", pwd); // Noncompliant
    }

    // Argument shapes, and one finding per call
    public void Shapes(string password, string apiKey)
    {
        _logger.LogInformation($"Pwd {password}"); // Noncompliant: interpolation
        _logger.LogInformation("Pwd " + password); // Noncompliant: concatenation
        Action a = () => _logger.LogInformation("Pwd {p}", password); // Noncompliant: lambda
        _logger.LogInformation("{a} {b}", password, apiKey); // Noncompliant: both arguments
        _logger.LogInformation("Pwd {p}", password!); // Noncompliant: null-forgiving
        _logger.LogInformation("Pwd {p}", (password)); // Noncompliant: parentheses
        _logger.LogInformation("Pwd {p}", (string)password); // Noncompliant: cast
        _logger.LogInformation("Pwd {p}", password ?? "<missing>"); // Noncompliant: null coalescing
        _logger.LogInformation("Pwd " /* label */ + password); // Noncompliant: comment before +
        _logger.LogInformation("Pwd " + /* label */ password); // Noncompliant: comment after +
    }

    public void ExpressionBodied(string apiKey) => _logger.LogInformation("Key {k}", apiKey); // Noncompliant
}
```

## Compliant Code Examples{% #compliant-code-examples %}

```csharp
public class UserController : Controller
{
    private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
    
    [HttpPost]
    public ActionResult Register(string username)
    {
        if (!string.IsNullOrEmpty(username))
        {
            string masked = username.Length > 2 ? username.Substring(0, 2) + "***" : "***";
            _logger.Warn("Registration attempt for user: " + masked);
        }
        return View();
    }
}
```

```csharp
using System;
using Microsoft.Extensions.Logging;
using NLog;

public class OrderService
{
    private readonly ILogger<OrderService> _logger;
    private static readonly NLog.Logger _nlog = LogManager.GetCurrentClassLogger();
    private readonly Validator validator;

    // Operational values
    public void Process(int retryCount, string orderId, long durationMs, int statusCode, string name, Exception ex)
    {
        _logger.LogInformation("Retry {n}", retryCount);
        _logger.LogInformation("Order {id} took {ms}ms", orderId, durationMs);
        _logger.LogWarning("Status {code} for {name}", statusCode, name);
        _logger.LogError(ex, "Order {id} failed", orderId);
    }

    // Values derived from a sensitive value
    public void Derived(string password, string token, string apiKey, int tokenCount)
    {
        _logger.LogInformation("Pwd {p}", Mask(password));
        _logger.LogInformation("Key {k}", Hash(apiKey));
        _logger.LogInformation("Pwd length {n}", password.Length);
        _logger.LogInformation($"Pwd length {password.Length}");
        _logger.LogInformation("Missing {n}", nameof(password));
        _logger.LogInformation("Has token {b}", token != null);
        _logger.LogInformation("Tokens {n}", tokenCount);
        _logger.LogInformation("Password reset requested");
    }

    // Calls that are not logging
    public void NotLogging(string password, double x)
    {
        validator.Error(password);
        Math.Log(x);
        MathF.Log((float)x);
    }
}
```

```csharp
using Microsoft.Extensions.Logging;

public class FileProcessor
{
    private readonly ILogger<FileProcessor> _logger;

    public void Finish(string fileName, string bucketName)
    {
        _logger.LogInformation("Finishing process for file {fileName} from bucket {bucketName}", fileName, bucketName);
    }

    public void Handle(Message message)
    {
        _logger.LogInformation("Skipped unsupported event {MessageType} (ID: {MessageId})", message.Type, message.Id);
    }
}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 