| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223 |
- #!/usr/bin/env tsx
- /**
- * 生产环境日志系统测试
- * 测试结构化日志和业务日志功能
- */
- import { ProductionLogger } from '../src/utils/ProductionLogger.js'
- import { existsSync, mkdirSync } from 'fs'
- async function testProductionLogger() {
- console.log('📝 测试生产环境日志系统')
- console.log('='.repeat(50))
- // 确保日志目录存在
- const logDir = './test-logs'
- if (!existsSync(logDir)) {
- mkdirSync(logDir, { recursive: true })
- }
- // 初始化生产日志器
- const logger = new ProductionLogger({
- level: 'debug',
- enableConsole: true,
- enableFile: true,
- logDir,
- maxFileSize: 1, // 1MB 用于测试轮转
- enableAudit: true,
- })
- console.log('\n🔧 测试基础日志功能:')
- // 测试不同级别的日志
- logger.debug('调试信息', { component: 'test' })
- logger.info('系统信息', { version: '1.0.0', environment: 'test' })
- logger.warn('警告信息', { reason: 'test-warning' })
- logger.error('错误信息', new Error('测试错误'), { context: 'test' })
- logger.critical('严重错误', new Error('严重测试错误'), { impact: 'high' })
- console.log('\n💼 测试业务日志功能:')
- // 测试交易日志
- logger.trade('下单', {
- exchange: 'binance',
- accountId: 'test-account-1',
- symbol: 'BTCUSDT',
- side: 'BUY',
- quantity: '0.001',
- price: '50000',
- orderId: 'test-order-123',
- })
- // 测试对冲日志
- logger.hedge('执行对冲', {
- sourceExchange: 'binance',
- targetExchange: 'pacifica',
- symbol: 'BTCUSDT',
- quantity: '0.001',
- reason: '价格差异套利',
- expectedProfit: '0.5',
- })
- // 测试账户日志
- logger.account('余额更新', {
- exchange: 'pacifica',
- accountId: 'test-account-2',
- previousBalance: '1000',
- newBalance: '999.5',
- change: '-0.5',
- })
- // 测试 WebSocket 日志
- logger.websocket('连接建立', {
- exchange: 'aster',
- event: 'connect',
- symbol: 'ETHUSDT',
- latency: 150,
- })
- // 测试性能日志
- logger.performance('订单执行延迟', 250, {
- exchange: 'binance',
- orderType: 'MARKET',
- symbol: 'BTCUSDT',
- })
- // 测试审计日志
- logger.audit('用户登录', {
- userId: 'test-user-1',
- exchange: 'binance',
- accountId: 'test-account-1',
- resource: 'trading-api',
- result: 'success',
- ipAddress: '192.168.1.100',
- })
- console.log('\n👥 测试子日志器:')
- // 创建子日志器
- const tradingLogger = logger.child('TRADING', {
- module: 'order-execution',
- version: '2.0.0',
- })
- tradingLogger.info('使用子日志器记录交易信息', {
- action: 'place-order',
- success: true,
- })
- const hedgeLogger = logger.child('HEDGING', {
- strategy: 'delta-neutral',
- riskLevel: 'low',
- })
- hedgeLogger.warn('对冲策略警告', {
- reason: 'spread-too-small',
- threshold: '0.1%',
- current: '0.05%',
- })
- console.log('\n📊 测试日志统计:')
- const stats = logger.getStats()
- console.log('日志器状态:', {
- 配置: stats.config,
- 当前日志文件: stats.currentLogFile,
- 文件大小: `${Math.round(stats.currentFileSize / 1024)}KB`,
- 流状态: stats.streamActive ? '活跃' : '关闭',
- })
- console.log('\n⏱️ 模拟高频日志 (测试性能):')
- const startTime = Date.now()
- for (let i = 0; i < 100; i++) {
- logger.info(`高频日志消息 ${i}`, {
- iteration: i,
- timestamp: Date.now(),
- randomValue: Math.random(),
- })
- }
- const duration = Date.now() - startTime
- console.log(`✅ 100条日志记录完成,耗时: ${duration}ms`)
- // 关闭日志器
- logger.close()
- console.log('\n✅ 日志器已关闭')
- }
- async function testLoggerPerformance() {
- console.log('\n⚡ 性能测试')
- console.log('='.repeat(30))
- const logger = new ProductionLogger({
- level: 'info',
- enableConsole: false, // 关闭控制台输出以测试纯文件性能
- enableFile: true,
- logDir: './test-logs',
- enableAudit: false,
- })
- const iterations = 1000
- const startTime = Date.now()
- // 模拟对冲交易系统的真实日志负载
- for (let i = 0; i < iterations; i++) {
- if (i % 10 === 0) {
- logger.trade('市场订单执行', {
- exchange: 'binance',
- symbol: 'BTCUSDT',
- side: Math.random() > 0.5 ? 'BUY' : 'SELL',
- quantity: (Math.random() * 0.01).toFixed(6),
- price: (50000 + Math.random() * 1000).toFixed(2),
- executionTime: Math.random() * 500,
- })
- }
- if (i % 25 === 0) {
- logger.hedge('对冲执行', {
- sourceExchange: 'binance',
- targetExchange: 'pacifica',
- symbol: 'BTCUSDT',
- netDelta: (Math.random() * 10 - 5).toFixed(4),
- hedgeQuantity: (Math.random() * 0.005).toFixed(6),
- })
- }
- logger.performance('系统延迟', Math.random() * 100, {
- component: 'order-router',
- load: Math.random(),
- })
- }
- const duration = Date.now() - startTime
- const logsPerSecond = ((iterations / duration) * 1000).toFixed(0)
- console.log(`📈 性能测试结果:`)
- console.log(` 日志条数: ${iterations}`)
- console.log(` 总耗时: ${duration}ms`)
- console.log(` 吞吐量: ${logsPerSecond} logs/sec`)
- console.log(` 平均延迟: ${(duration / iterations).toFixed(2)}ms/log`)
- logger.close()
- }
- async function main() {
- try {
- console.log('🚀 开始生产环境日志系统测试\n')
- await testProductionLogger()
- await testLoggerPerformance()
- console.log('\n🎉 所有日志测试完成!')
- console.log('💡 提示: 查看 ./test-logs 目录中的日志文件')
- } catch (error) {
- console.error('❌ 测试失败:', error)
- process.exit(1)
- }
- }
- // 运行测试
- if (import.meta.url === `file://${process.argv[1]}`) {
- main()
- }
|