also looking at this
Deploy: uniform auth session model (main → production)
#7
282 files
+3028
-64856
| @@ -1,244 +0,0 @@ | ||
| 1 | # Logging | |
| 2 | ||
| 3 | Stacks provides a powerful logging system built on [Clarity](https://github.com/stacksjs/clarity), offering structured logging, multiple output channels, and beautiful console formatting. | |
| 4 | ||
| 5 | ## Overview | |
| 6 | ||
| 7 | The Stacks logging system helps you: | |
| 8 | ||
| 9 | - **Debug** - Track application behavior and issues | |
| 10 | - **Monitor** - Log errors and exceptions for observability | |
| 11 | - **Audit** - Create audit trails for compliance | |
| 12 | - **Analyze** - Understand application performance | |
| 13 | ||
| 14 | ## Quick Start | |
| 15 | ||
| 16 | ```typescript | |
| 17 | import { log } from '@stacksjs/logging' | |
| 18 | ||
| 19 | // Basic logging | |
| 20 | log.info('User logged in', { userId: 123 }) | |
| 21 | log.warn('Rate limit approaching', { current: 90, max: 100 }) | |
| 22 | log.error('Payment failed', { orderId: 456, error: 'Card declined' }) | |
| 23 | log.debug('Query executed', { sql: 'SELECT * FROM users', ms: 45 }) | |
| 24 | log.success('Order completed', { orderId: 789 }) | |
| 25 | ``` | |
| 26 | ||
| 27 | ## Log Levels | |
| 28 | ||
| 29 | Stacks supports standard log levels, ordered from most to least severe: | |
| 30 | ||
| 31 | | Level | Method | Description | Use Case | | |
| 32 | |-------|--------|-------------|----------| | |
| 33 | | `error` | `log.error()` | Critical errors | Exceptions, failed operations | | |
| 34 | | `warn` | `log.warn()` | Warning conditions | Deprecations, approaching limits | | |
| 35 | | `info` | `log.info()` | Informational | User actions, state changes | | |
| 36 | | `debug` | `log.debug()` | Debug details | Development, troubleshooting | | |
| 37 | | `success` | `log.success()` | Success confirmations | Completed operations | | |
| 38 | ||
| 39 | ### Setting Log Level | |
| 40 | ||
| 41 | Set the minimum log level via environment variable: | |
| 42 | ||
| 43 | ```bash | |
| 44 | # .env | |
| 45 | LOG_LEVEL=debug # Shows all logs | |
| 46 | LOG_LEVEL=info # Shows info, warn, error, success | |
| 47 | LOG_LEVEL=warn # Shows warn and error only | |
| 48 | LOG_LEVEL=error # Shows only errors | |
| 49 | ``` | |
| 50 | ||
| 51 | ## Structured Logging | |
| 52 | ||
| 53 | ### Logging with Context | |
| 54 | ||
| 55 | Always log structured data for better analysis: | |
| 56 | ||
| 57 | ```typescript | |
| 58 | // Good: Structured data | |
| 59 | log.info('Order processed', { | |
| 60 | orderId: order.id, | |
| 61 | userId: order.userId, | |
| 62 | total: order.total, | |
| 63 | items: order.items.length, | |
| 64 | }) | |
| 65 | ||
| 66 | // Avoid: String concatenation | |
| 67 | log.info(`Order ${order.id} processed for user ${order.userId}`) | |
| 68 | ``` | |
| 69 | ||
| 70 | ### Error Logging | |
| 71 | ||
| 72 | ```typescript | |
| 73 | try { | |
| 74 | await processPayment(order) | |
| 75 | } catch (error) { | |
| 76 | log.error('Payment failed', { | |
| 77 | error: error.message, | |
| 78 | stack: error.stack, | |
| 79 | orderId: order.id, | |
| 80 | amount: order.total, | |
| 81 | }) | |
| 82 | throw error | |
| 83 | } | |
| 84 | ``` | |
| 85 | ||
| 86 | ## Helper Functions | |
| 87 | ||
| 88 | ### dump() - Debug Output | |
| 89 | ||
| 90 | Output values without stopping execution: | |
| 91 | ||
| 92 | ```typescript | |
| 93 | import { dump } from '@stacksjs/logging' | |
| 94 | ||
| 95 | const data = await fetchData() | |
| 96 | dump(data) // Logs to debug level | |
| 97 | // Execution continues | |
| 98 | ``` | |
| 99 | ||
| 100 | ### dd() - Dump and Die | |
| 101 | ||
| 102 | Output values and stop execution (useful for debugging): | |
| 103 | ||
| 104 | ```typescript | |
| 105 | import { dd } from '@stacksjs/logging' | |
| 106 | ||
| 107 | const result = await processData() | |
| 108 | dd(result) // Logs and exits | |
| 109 | // Code below never executes | |
| 110 | ``` | |
| 111 | ||
| 112 | ### Performance Timing | |
| 113 | ||
| 114 | ```typescript | |
| 115 | const endTimer = log.time('database-query') | |
| 116 | ||
| 117 | const users = await db.select().from('users').execute() | |
| 118 | ||
| 119 | await endTimer({ rowCount: users.length }) | |
| 120 | // Output: database-query completed in 45ms { rowCount: 100 } | |
| 121 | ``` | |
| 122 | ||
| 123 | ## Configuration | |
| 124 | ||
| 125 | Configure logging in `stacks.config.ts`: | |
| 126 | ||
| 127 | ```typescript | |
| 128 | export default { | |
| 129 | logging: { | |
| 130 | // Minimum log level | |
| 131 | level: process.env.LOG_LEVEL || 'info', | |
| 132 | ||
| 133 | // Log file directory | |
| 134 | logDirectory: 'storage/logs', | |
| 135 | ||
| 136 | // Write logs to file | |
| 137 | writeToFile: true, | |
| 138 | ||
| 139 | // Show tags in output (e.g., [STACKS]) | |
| 140 | showTags: false, | |
| 141 | ||
| 142 | // Colorful console output | |
| 143 | fancy: process.env.NODE_ENV !== 'production', | |
| 144 | ||
| 145 | // Date format | |
| 146 | dateFormat: 'YYYY-MM-DD HH:mm:ss', | |
| 147 | ||
| 148 | // Sensitive fields to redact | |
| 149 | redact: ['password', 'token', 'secret', 'creditCard'], | |
| 150 | } | |
| 151 | } | |
| 152 | ``` | |
| 153 | ||
| 154 | ## Log Channels | |
| 155 | ||
| 156 | ### Console Channel | |
| 157 | ||
| 158 | Logs are output to the terminal with beautiful formatting: | |
| 159 | ||
| 160 | ```typescript | |
| 161 | log.info('Request received', { | |
| 162 | method: 'GET', | |
| 163 | path: '/api/users', | |
| 164 | ip: '192.168.1.1' | |
| 165 | }) | |
| 166 | ||
| 167 | // Output: | |
| 168 | // [2024-01-15 10:30:45] INFO: Request received | |
| 169 | // method: GET | |
| 170 | // path: /api/users | |
| 171 | // ip: 192.168.1.1 | |
| 172 | ``` | |
| 173 | ||
| 174 | ### File Channel | |
| 175 | ||
| 176 | Logs are written to files in `storage/logs/`: | |
| 177 | ||
| 178 | ``` | |
| 179 | storage/logs/ | |
| 180 | stacks.log # Main log file | |
| 181 | stacks-2024-01-15.log # Daily rotation | |
| 182 | errors.log # Error-only log | |
| 183 | ``` | |
| 184 | ||
| 185 | ## Contextual Logging | |
| 186 | ||
| 187 | ### Request Context | |
| 188 | ||
| 189 | Add context to all logs within a request: | |
| 190 | ||
| 191 | ```typescript | |
| 192 | // In middleware | |
| 193 | export async function loggingMiddleware(request, next) { | |
| 194 | const requestId = crypto.randomUUID() | |
| 195 | ||
| 196 | const scopedLog = log.withContext({ | |
| 197 | requestId, | |
| 198 | path: request.url, | |
| 199 | method: request.method, | |
| 200 | }) | |
| 201 | ||
| 202 | scopedLog.info('Request started') | |
| 203 | ||
| 204 | try { | |
| 205 | const response = await next() | |
| 206 | scopedLog.info('Request completed', { status: response.status }) | |
| 207 | return response | |
| 208 | } catch (error) { | |
| 209 | scopedLog.error('Request failed', { error: error.message }) | |
| 210 | throw error | |
| 211 | } | |
| 212 | } | |
| 213 | ``` | |
| 214 | ||
| 215 | ## Best Practices | |
| 216 | ||
| 217 | ### DO | |
| 218 | ||
| 219 | - **Use structured logging** - Pass objects, not concatenated strings | |
| 220 | - **Include context** - Add relevant IDs (user, request, order) | |
| 221 | - **Log at appropriate levels** - Don't log debug info at error level | |
| 222 | - **Redact sensitive data** - Never log passwords, tokens, or PII | |
| 223 | ||
| 224 | ### DON'T | |
| 225 | ||
| 226 | - **Don't log sensitive data** - Passwords, tokens, credit cards | |
| 227 | - **Don't over-log** - Too many logs make debugging harder | |
| 228 | - **Don't log in tight loops** - Can cause performance issues | |
| 229 | ||
| 230 | ## Related Resources | |
| 231 | ||
| 232 | ### Underlying Libraries | |
| 233 | ||
| 234 | - **[Clarity](https://github.com/stacksjs/clarity)** - The logging library powering Stacks logging | |
| 235 | ||
| 236 | ### Related Stacks Packages | |
| 237 | ||
| 238 | - **[Error Handling Package](/packages/error-handling)** - Error handling and logging | |
| 239 | - **[Config Package](/packages/config)** - Configure log settings | |
| 240 | ||
| 241 | ### Related Guides | |
| 242 | ||
| 243 | - **[Error Handling](/basics/error-handling)** - Handling and logging errors | |
| 244 | - **[Debugging](/guide/debugging)** - Debug techniques | |