production_logger_test.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. #!/usr/bin/env tsx
  2. /**
  3. * 生产环境日志系统测试
  4. * 测试结构化日志和业务日志功能
  5. */
  6. import { ProductionLogger } from '../src/utils/ProductionLogger.js'
  7. import { existsSync, mkdirSync } from 'fs'
  8. async function testProductionLogger() {
  9. console.log('📝 测试生产环境日志系统')
  10. console.log('='.repeat(50))
  11. // 确保日志目录存在
  12. const logDir = './test-logs'
  13. if (!existsSync(logDir)) {
  14. mkdirSync(logDir, { recursive: true })
  15. }
  16. // 初始化生产日志器
  17. const logger = new ProductionLogger({
  18. level: 'debug',
  19. enableConsole: true,
  20. enableFile: true,
  21. logDir,
  22. maxFileSize: 1, // 1MB 用于测试轮转
  23. enableAudit: true,
  24. })
  25. console.log('\n🔧 测试基础日志功能:')
  26. // 测试不同级别的日志
  27. logger.debug('调试信息', { component: 'test' })
  28. logger.info('系统信息', { version: '1.0.0', environment: 'test' })
  29. logger.warn('警告信息', { reason: 'test-warning' })
  30. logger.error('错误信息', new Error('测试错误'), { context: 'test' })
  31. logger.critical('严重错误', new Error('严重测试错误'), { impact: 'high' })
  32. console.log('\n💼 测试业务日志功能:')
  33. // 测试交易日志
  34. logger.trade('下单', {
  35. exchange: 'binance',
  36. accountId: 'test-account-1',
  37. symbol: 'BTCUSDT',
  38. side: 'BUY',
  39. quantity: '0.001',
  40. price: '50000',
  41. orderId: 'test-order-123',
  42. })
  43. // 测试对冲日志
  44. logger.hedge('执行对冲', {
  45. sourceExchange: 'binance',
  46. targetExchange: 'pacifica',
  47. symbol: 'BTCUSDT',
  48. quantity: '0.001',
  49. reason: '价格差异套利',
  50. expectedProfit: '0.5',
  51. })
  52. // 测试账户日志
  53. logger.account('余额更新', {
  54. exchange: 'pacifica',
  55. accountId: 'test-account-2',
  56. previousBalance: '1000',
  57. newBalance: '999.5',
  58. change: '-0.5',
  59. })
  60. // 测试 WebSocket 日志
  61. logger.websocket('连接建立', {
  62. exchange: 'aster',
  63. event: 'connect',
  64. symbol: 'ETHUSDT',
  65. latency: 150,
  66. })
  67. // 测试性能日志
  68. logger.performance('订单执行延迟', 250, {
  69. exchange: 'binance',
  70. orderType: 'MARKET',
  71. symbol: 'BTCUSDT',
  72. })
  73. // 测试审计日志
  74. logger.audit('用户登录', {
  75. userId: 'test-user-1',
  76. exchange: 'binance',
  77. accountId: 'test-account-1',
  78. resource: 'trading-api',
  79. result: 'success',
  80. ipAddress: '192.168.1.100',
  81. })
  82. console.log('\n👥 测试子日志器:')
  83. // 创建子日志器
  84. const tradingLogger = logger.child('TRADING', {
  85. module: 'order-execution',
  86. version: '2.0.0',
  87. })
  88. tradingLogger.info('使用子日志器记录交易信息', {
  89. action: 'place-order',
  90. success: true,
  91. })
  92. const hedgeLogger = logger.child('HEDGING', {
  93. strategy: 'delta-neutral',
  94. riskLevel: 'low',
  95. })
  96. hedgeLogger.warn('对冲策略警告', {
  97. reason: 'spread-too-small',
  98. threshold: '0.1%',
  99. current: '0.05%',
  100. })
  101. console.log('\n📊 测试日志统计:')
  102. const stats = logger.getStats()
  103. console.log('日志器状态:', {
  104. 配置: stats.config,
  105. 当前日志文件: stats.currentLogFile,
  106. 文件大小: `${Math.round(stats.currentFileSize / 1024)}KB`,
  107. 流状态: stats.streamActive ? '活跃' : '关闭',
  108. })
  109. console.log('\n⏱️ 模拟高频日志 (测试性能):')
  110. const startTime = Date.now()
  111. for (let i = 0; i < 100; i++) {
  112. logger.info(`高频日志消息 ${i}`, {
  113. iteration: i,
  114. timestamp: Date.now(),
  115. randomValue: Math.random(),
  116. })
  117. }
  118. const duration = Date.now() - startTime
  119. console.log(`✅ 100条日志记录完成,耗时: ${duration}ms`)
  120. // 关闭日志器
  121. logger.close()
  122. console.log('\n✅ 日志器已关闭')
  123. }
  124. async function testLoggerPerformance() {
  125. console.log('\n⚡ 性能测试')
  126. console.log('='.repeat(30))
  127. const logger = new ProductionLogger({
  128. level: 'info',
  129. enableConsole: false, // 关闭控制台输出以测试纯文件性能
  130. enableFile: true,
  131. logDir: './test-logs',
  132. enableAudit: false,
  133. })
  134. const iterations = 1000
  135. const startTime = Date.now()
  136. // 模拟对冲交易系统的真实日志负载
  137. for (let i = 0; i < iterations; i++) {
  138. if (i % 10 === 0) {
  139. logger.trade('市场订单执行', {
  140. exchange: 'binance',
  141. symbol: 'BTCUSDT',
  142. side: Math.random() > 0.5 ? 'BUY' : 'SELL',
  143. quantity: (Math.random() * 0.01).toFixed(6),
  144. price: (50000 + Math.random() * 1000).toFixed(2),
  145. executionTime: Math.random() * 500,
  146. })
  147. }
  148. if (i % 25 === 0) {
  149. logger.hedge('对冲执行', {
  150. sourceExchange: 'binance',
  151. targetExchange: 'pacifica',
  152. symbol: 'BTCUSDT',
  153. netDelta: (Math.random() * 10 - 5).toFixed(4),
  154. hedgeQuantity: (Math.random() * 0.005).toFixed(6),
  155. })
  156. }
  157. logger.performance('系统延迟', Math.random() * 100, {
  158. component: 'order-router',
  159. load: Math.random(),
  160. })
  161. }
  162. const duration = Date.now() - startTime
  163. const logsPerSecond = ((iterations / duration) * 1000).toFixed(0)
  164. console.log(`📈 性能测试结果:`)
  165. console.log(` 日志条数: ${iterations}`)
  166. console.log(` 总耗时: ${duration}ms`)
  167. console.log(` 吞吐量: ${logsPerSecond} logs/sec`)
  168. console.log(` 平均延迟: ${(duration / iterations).toFixed(2)}ms/log`)
  169. logger.close()
  170. }
  171. async function main() {
  172. try {
  173. console.log('🚀 开始生产环境日志系统测试\n')
  174. await testProductionLogger()
  175. await testLoggerPerformance()
  176. console.log('\n🎉 所有日志测试完成!')
  177. console.log('💡 提示: 查看 ./test-logs 目录中的日志文件')
  178. } catch (error) {
  179. console.error('❌ 测试失败:', error)
  180. process.exit(1)
  181. }
  182. }
  183. // 运行测试
  184. if (import.meta.url === `file://${process.argv[1]}`) {
  185. main()
  186. }