Logging Rules
1. Log Level Usage
Level Definitions
| Level |
Purpose |
Examples |
| ERROR |
Critical issues needing attention |
DB connection failed, payment error |
| WARN |
Potential problems, attention |
Deprecated API call, retry in progress |
| INFO |
Major business events |
User login, order created |
| DEBUG |
Development/debugging details |
Variable values, method entry/exit |
| TRACE |
Very detailed debugging info |
Full call stack, timing info |
Level Selection Criteria
ERROR: Service disruption or data loss possible
WARN: Normal operation but monitoring needed
INFO: Business flow tracking
DEBUG: Root cause analysis when issues occur
TRACE: Performance analysis or deep debugging
2. Log Message Format
Basic Structure
[timestamp] [level] [traceId] [class:method] - message {context}
Example
2024-01-15T10:30:45.123Z INFO [abc123] [UserService:login] - User login successful {"userId": "user-001", "ip": "192.168.1.1"}
2024-01-15T10:31:00.456Z ERROR [abc123] [PaymentService:process] - Payment failed {"orderId": "order-123", "errorCode": "INSUFFICIENT_BALANCE"}
Required Fields
| Field |
Description |
| timestamp |
ISO 8601 format, UTC preferred |
| level |
Log level |
| traceId |
Unique ID for request tracing |
| location |
ClassName:methodName |
| message |
Human-readable message |
| context |
Additional context in JSON format |
3. Sensitive Data Handling
Never Include in Logs
- Passwords
- API keys, secret keys
- Access tokens, refresh tokens
- Credit card numbers, CVV
- National ID, passport numbers
- Bank account numbers
- Biometric data
- Precise location data
Masking Rules
| Data Type |
Masking Method |
Example |
| Email |
First 2 chars + *** + @ + domain |
ab***@example.com |
| Phone |
Mask middle 4 digits |
010-****-1234 |
| Name |
First char + *** |
J*** |
| Credit Card |
Show last 4 digits only |
****-****-****-1234 |
| API Key |
First 4 chars + *** |
sk-****... |
| Address |
Show city/region only |
Seoul *** |
| IP Address |
Mask last octet |
192.168.1.*** |
Masking Implementation Example
// Email masking
function maskEmail(email: string): string {
const [localPart, domain] = email.split('@');
const masked = localPart.slice(0, 2) + '***';
return `${masked}@${domain}`;
}
// Phone masking
function maskPhone(phone: string): string {
return phone.replace(/(\d{3})-(\d{4})-(\d{4})/, '$1-****-$3');
}
// Credit card masking
function maskCardNumber(cardNumber: string): string {
const lastFour = cardNumber.slice(-4);
return `****-****-****-${lastFour}`;
}
4. Structured Logging
JSON Log Format
{
"timestamp": "2024-01-15T10:30:45.123Z",
"level": "INFO",
"traceId": "abc123",
"service": "user-service",
"class": "UserService",
"method": "login",
"message": "User login successful",
"context": {
"userId": "user-001",
"loginMethod": "password",
"durationMs": 150
}
}
Context Information Inclusion
| Info |
Include |
Note |
| userId |
Yes |
No masking needed |
| requestId |
Yes |
For tracing |
| duration |
Yes |
Performance monitoring |
| stack trace |
Yes (ERROR) |
Error debugging |
| password |
No |
Never include |
| token |
No |
Never include |
5. Logging Anti-Patterns
Patterns to Avoid
// Bad: Exposing sensitive info
logger.info(`User login: ${email}, password: ${password}`);
// Good: Exclude sensitive info
logger.info(`User login successful`, { userId: user.id });
// Bad: Error log without stack trace
logger.error(`Payment failed: ${error.message}`);
// Good: Include stack trace
logger.error(`Payment failed`, { error: error.stack, orderId });
// Bad: Excessive DEBUG logs
logger.debug(`Processing item 1`);
logger.debug(`Processing item 2`);
// ... thousands of logs
// Good: Log in meaningful batches
logger.debug(`Processing batch`, { itemCount: items.length });
// Bad: Wrong log level usage
logger.error(`User not found: ${userId}`); // Business exception, not ERROR
// Good: Appropriate level
logger.info(`User not found`, { userId }); // Or WARN
6. Performance Considerations
- Disable DEBUG/TRACE in production by default
- Log in batches for large data processing
- Always mask sensitive info regardless of log level
- Use structured logs (JSON) for efficient searching
Log Volume Guidelines
| Environment |
INFO+ |
DEBUG |
TRACE |
| Development |
Yes |
Yes |
Yes |
| Staging |
Yes |
Yes |
No |
| Production |
Yes |
No |
No |
1---2name: logging3description: Logging standards, structured logging, and sensitive data handling. Covers log levels (DEBUG, INFO, WARN, ERROR, TRACE), MDC (Mapped Diagnostic Context), correlation ID propagation, log format standardization, sensitive data masking, and log aggregation best practices. Use when writing logging code, configuring log frameworks (Logback, Log4j2), reviewing log output, or implementing request tracing with correlation IDs.4license: MIT5---67# Logging Rules89## 1. Log Level Usage1011### Level Definitions1213| Level | Purpose | Examples |14| ------ | --------------------------------- | ------------------------------------- |15| ERROR | Critical issues needing attention | DB connection failed, payment error |16| WARN | Potential problems, attention | Deprecated API call, retry in progress|17| INFO | Major business events | User login, order created |18| DEBUG | Development/debugging details | Variable values, method entry/exit |19| TRACE | Very detailed debugging info | Full call stack, timing info |2021### Level Selection Criteria2223```text24ERROR: Service disruption or data loss possible25WARN: Normal operation but monitoring needed26INFO: Business flow tracking27DEBUG: Root cause analysis when issues occur28TRACE: Performance analysis or deep debugging29```3031---3233## 2. Log Message Format3435### Basic Structure3637```text38[timestamp] [level] [traceId] [class:method] - message {context}39```4041### Example4243```text442024-01-15T10:30:45.123Z INFO [abc123] [UserService:login] - User login successful {"userId": "user-001", "ip": "192.168.1.1"}452024-01-15T10:31:00.456Z ERROR [abc123] [PaymentService:process] - Payment failed {"orderId": "order-123", "errorCode": "INSUFFICIENT_BALANCE"}46```4748### Required Fields4950| Field | Description |51| ---------- | --------------------------------- |52| timestamp | ISO 8601 format, UTC preferred |53| level | Log level |54| traceId | Unique ID for request tracing |55| location | ClassName:methodName |56| message | Human-readable message |57| context | Additional context in JSON format |5859---6061## 3. Sensitive Data Handling6263### Never Include in Logs6465- Passwords66- API keys, secret keys67- Access tokens, refresh tokens68- Credit card numbers, CVV69- National ID, passport numbers70- Bank account numbers71- Biometric data72- Precise location data7374### Masking Rules7576| Data Type | Masking Method | Example |77| -------------- | ------------------------------- | ------------------------ |78| Email | First 2 chars + *** + @ + domain| `ab***@example.com` |79| Phone | Mask middle 4 digits | `010-****-1234` |80| Name | First char + *** | `J***` |81| Credit Card | Show last 4 digits only | `****-****-****-1234` |82| API Key | First 4 chars + *** | `sk-****...` |83| Address | Show city/region only | `Seoul ***` |84| IP Address | Mask last octet | `192.168.1.***` |8586### Masking Implementation Example8788```typescript89// Email masking90function maskEmail(email: string): string {91 const [localPart, domain] = email.split('@');92 const masked = localPart.slice(0, 2) + '***';93 return `${masked}@${domain}`;94}9596// Phone masking97function maskPhone(phone: string): string {98 return phone.replace(/(\d{3})-(\d{4})-(\d{4})/, '$1-****-$3');99}100101// Credit card masking102function maskCardNumber(cardNumber: string): string {103 const lastFour = cardNumber.slice(-4);104 return `****-****-****-${lastFour}`;105}106```107108---109110## 4. Structured Logging111112### JSON Log Format113114```json115{116 "timestamp": "2024-01-15T10:30:45.123Z",117 "level": "INFO",118 "traceId": "abc123",119 "service": "user-service",120 "class": "UserService",121 "method": "login",122 "message": "User login successful",123 "context": {124 "userId": "user-001",125 "loginMethod": "password",126 "durationMs": 150127 }128}129```130131### Context Information Inclusion132133| Info | Include | Note |134| ----------- | ------------ | ------------------------- |135| userId | Yes | No masking needed |136| requestId | Yes | For tracing |137| duration | Yes | Performance monitoring |138| stack trace | Yes (ERROR) | Error debugging |139| password | No | Never include |140| token | No | Never include |141142---143144## 5. Logging Anti-Patterns145146### Patterns to Avoid147148```typescript149// Bad: Exposing sensitive info150logger.info(`User login: ${email}, password: ${password}`);151152// Good: Exclude sensitive info153logger.info(`User login successful`, { userId: user.id });154155// Bad: Error log without stack trace156logger.error(`Payment failed: ${error.message}`);157158// Good: Include stack trace159logger.error(`Payment failed`, { error: error.stack, orderId });160161// Bad: Excessive DEBUG logs162logger.debug(`Processing item 1`);163logger.debug(`Processing item 2`);164// ... thousands of logs165166// Good: Log in meaningful batches167logger.debug(`Processing batch`, { itemCount: items.length });168169// Bad: Wrong log level usage170logger.error(`User not found: ${userId}`); // Business exception, not ERROR171172// Good: Appropriate level173logger.info(`User not found`, { userId }); // Or WARN174```175176---177178## 6. Performance Considerations179180- Disable DEBUG/TRACE in production by default181- Log in batches for large data processing182- Always mask sensitive info regardless of log level183- Use structured logs (JSON) for efficient searching184185### Log Volume Guidelines186187| Environment | INFO+ | DEBUG | TRACE |188| ----------- | ----- | ----- | ----- |189| Development | Yes | Yes | Yes |190| Staging | Yes | Yes | No |191| Production | Yes | No | No |