זה דף locallLoggerMiddleware.ts:import winston from 'winston';
import path from 'path';
import fs from 'fs';
import express, { Request, Response, NextFunction } from 'express';
import axios from 'axios';  // נשתמש ב-axios לשלוח את הלוגים ל-Coralogix
// import { Logger } from 'coralogix-logger'; // או כל מערכת לוגים אחרת
// import express from 'express';
// const app = express();

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

// Create a logs folder if it does not exist.
const logsDirectory = path.join(__dirname, 'logs');
if (!fs.existsSync(logsDirectory)) {
  fs.mkdirSync(logsDirectory);
}

// Custom log format
// const logFormat = printf(({ timestamp, level, message, req }: { timestamp: string, level: string, message: string, req: Request }) => {
//   return `${timestamp} [${level}] - Method: ${req.method} | URL: ${req.originalUrl}: ${message}`;
// });
const logFormat = printf(({ timestamp, level, message }) => {
  return `${timestamp} [${level}] - ${message}`;
});

 // Custom colors for each level
// const customColors = {
//   info: 'green',
//   error: 'red',
//   warn: 'yellow',
//   debug: 'magenta',
// };

// // Adding colors to the logo manager
// winston.addColors(customColors);

// Create the logger with transports (to file and screen)
const logger = winston.createLogger({
  level: 'info', // Default to log level
  format: combine(
   timestamp(),
    colorize({ all: true }), // Coloring all the logos
    logFormat
  ),
  transports: [
    // error to-error.log
    new winston.transports.File({filename: path.join(logsDirectory, 'error.log'),level: 'error', 
    }),
    // Information logs
    new winston.transports.File({filename: path.join(logsDirectory, 'info.log'),level: 'info' 
    }),
    // new winston.transports.File({
    //   filename: path.join(logsDirectory, 'info.log'),
    //   level: 'debug' // לוגים של דבגים
    // }),
    new winston.transports.File({filename: path.join(logsDirectory, 'combined.log'), // כל הלוגים לcombined.log
    }),
    // Only in production, send logs to Coralogix
    ...(process.env.NODE_ENV === 'production' ? [
      new winston.transports.Http({
        level: 'info',
        format: winston.format.json(),
        host: 'api.coralogix.com',
        port: 443,
        path: '/api/v1/logs',
        headers: {
          'Authorization': `Bearer ${process.env.CORALOGIX_API_KEY}`,
        },
        // Format the log body for Coralogix (adjust as needed)
        
      // אין body כאן, נשלח את הלוגים עם axios בהמשך
        
        // body: (log: any) => {
        //   return JSON.stringify({
        //     logs: [
        //       {
        //         timestamp: log.timestamp,
        //         severity: log.level,
        //         message: log.message,
        //       }
        //     ]
        //   });
        // }
      })
    ] : []),
  ],
});


// If we are not in production, we will add logs to the screen
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: combine(
      colorize(),
      simple()
    )
  }));
}


// Manage the middleware that will write the request details and status
//  app.use((req, res, next) => {
//   const start = Date.now();
export function loggerMiddleware(req: Request, res: Response, next: NextFunction)  {
    const start = Date.now();

// Create a log message before executing the request
  const logMessage = `Incoming Request: Method: ${req.method} | URL: ${req.originalUrl} | Params: ${JSON.stringify(req.params)} | Query: ${JSON.stringify(req.query)} | Body: ${JSON.stringify(req.body)}`;

// Register the request before it ends
  logger.info(logMessage);

// End request, after response status is received
  res.on('finish', () => {
    const duration = Date.now() - start;
    const logLevel = res.statusCode >= 400 ? 'error' : 'info';
    const logMessageAfter = `Completed Request: Method: ${req.method} | URL: ${req.originalUrl} | Status: ${res.statusCode} | Duration: ${duration}ms`;

// Logs that Registered after the request is complete
    logger[logLevel](logMessageAfter);
  
    
    // לשלוח את הלוגים ל-Coralogix בסביבת production
    if (process.env.NODE_ENV === 'production') {
      const logData = {
        timestamp: new Date().toISOString(),
        severity: logLevel,
        message: logMessageAfter,
      };

      axios.post('https://api.coralogix.com/api/v1/logs', {
        logs: [logData]
      }, {
        headers: {
          'Authorization': `Bearer ${process.env.CORALOGIX_API_KEY}`,
        },
      }).then(response => {
        console.log('Logs sent to Coralogix', response.data);
      }).catch(error => {
        console.error('Error sending logs to Coralogix:', error);
      });
    }
  });


  next();
};
// )
export {  logger };

// //send to-Coralogix API
//     ...(process.env.NODE_ENV === 'production' ? [
//       new winston.transports.Http({
//         level: 'info',
//         format: winston.format.json(),
//         // The details of the definition of Coralogix
//         host: 'api.coralogix.com',
//         port: 443,
//         path: '/api/v1/logs',
//         headers: {
//           'Authorization': `Bearer ${process.env.CORALOGIX_API_KEY}`,  // Coralogix API Key
//         },
//         Body: (log: any) => {
//           // כאן תוכל להתאים את המבנה של הלוגים לפי דרישות Coralogix
//           return JSON.stringify({
//             logs: [
//               {
//                 timestamp: log.timestamp,
//                 severity: log.level,
//                 message: log.message,
//               }
//             ]
//           });
//         }
//       })
//     ] : []), וזה דף app.ts:import express from 'express'; 
import { loggerMiddleware, logger } from './locallLoggerMiddleware';


const app = express();

app.use(express.json()); // אם אתה רוצה שתוכן גוף יפורס
app.use(loggerMiddleware);

// דוגמת נתיב GET
app.get('/', (req, res) => {
  res.send('Hello, world!');
});

// התחלת השרת
app.listen(3000, () => {
  logger.info('Server started on port 3000');
}); איך אני מריצה כדי לראות את התוצאות בדפי הלוג וכן איפה אני מוסיפה עוד בקשות HTTP כדי לראות אם זה באמת עובד