# How do I keep API keys and passwords out of logs and error messages?
Source: https://ruststudio.org/community/t/15/how-do-i-keep-api-keys-and-passwords-out-of-logs-and-error-messages
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, Windows 11
Category: Help and questions | Kind: FAQ | Tags: security, logging, configuration | Views: 0

## Short answer
Wrap secrets in a type whose Debug and Display print a placeholder, so printing a struct that holds one cannot leak it. Read the secret from an environment variable, never from source code, and expose the real value only through one explicit method at the place that sends it.

## Answer
## Answer
Most leaks are accidents: a `{:?}` print of a config struct, an error message that includes a URL with a password in it. A newtype that refuses to print its content turns the accident into a harmless placeholder.

```rust title=src/main.rs
use std::fmt;

/// A value that never prints itself. The only way to read it is the explicit `expose` call.
struct Secret(String);

impl Secret {
    fn from_env(name: &str) -> Option<Secret> {
        std::env::var(name).ok().filter(|v| !v.is_empty()).map(Secret)
    }
    fn expose(&self) -> &str {
        &self.0
    }
}
impl fmt::Debug for Secret {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("Secret(<redacted>)")
    }
}
impl fmt::Display for Secret {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("<redacted>")
    }
}

#[derive(Debug)]
struct Config {
    api_url: String,
    api_key: Secret,
}

fn main() {
    let cfg = Config { api_url: "https://api.example.test".into(), api_key: Secret("sk-12345".into()) };
    println!("{cfg:?}");
    println!("key = {}", cfg.api_key);
    println!("length = {}", cfg.api_key.expose().len());
    println!("{}", Secret::from_env("A_NAME_THAT_IS_NOT_SET").is_none());
}
```

```text
Config { api_url: "https://api.example.test", api_key: Secret(<redacted>) }
key = <redacted>
length = 8
true
```

(The compiler warns that `api_url` is never read in this demo; in a real program it would be used.)

## How to do it
1. Store secrets in environment variables or a file outside the repository, and read them once at start-up.
2. Wrap each in a type like `Secret` and derive `Debug` on the structs that hold it, as above.
3. Call `expose()` only where the value is sent (an HTTP header, a database connection).
4. Do not put the secret in URLs (`https://user:password@host`): URLs end up in logs and error messages.
5. Check `.gitignore` for the files that hold secrets, and rotate any key that was ever committed.

## Common mistakes
- Believing that a secret in an environment variable is safe from every log. It is only safe if nothing prints the environment.
- Implementing `Clone` and `Serialize` for `Secret` without thinking: a serializer can write it out. Leave those off unless needed.
- Deleting a leaked key from Git history and keeping it in use. Treat any leaked key as compromised and replace it.

## Related questions
### Does a crate exist for this?
Yes, crates such as `secrecy` provide a similar wrapper, and also clear the memory when it is dropped. The example above shows the idea in about twenty lines.

## Sources
- Standard library, `std::fmt::Debug`: https://doc.rust-lang.org/std/fmt/trait.Debug.html
