import winston from 'winston'

const { combine, timestamp, printf, colorize } = winston.format

const logFormat = printf(({ level, message, timestamp }) => {
  return `${timestamp} [${level}] ${message}`
})

// 保持向后兼容的 Winston logger，添加EPIPE错误处理
const winstonLogger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  format: combine(timestamp(), logFormat),
  transports: [
    new winston.transports.Console({
      format: combine(colorize(), timestamp(), logFormat),
      handleExceptions: false,
      handleRejections: false,
    }),
  ],
  exitOnError: false,
})

// 处理EPIPE错误，避免进程崩溃
winstonLogger.on('error', error => {
  if ((error as any).code === 'EPIPE') {
    // 静默处理EPIPE错误，不打印到控制台
    return
  }
  // 其他错误仍然处理
  console.error('Winston logger error:', error.message)
})

// 处理stdout/stderr的EPIPE错误
process.stdout.on('error', error => {
  if (error.code === 'EPIPE') {
    process.exit(0)
  }
})

process.stderr.on('error', error => {
  if (error.code === 'EPIPE') {
    process.exit(0)
  }
})

// 统一使用Winston日志器
export const logger = winstonLogger

// 默认导出
export default logger
