# 📋 Logging Guide - Finding Error Logs on cPanel

## ✅ What Was Added

Comprehensive logging has been added throughout the application to help debug 503 errors and other issues:

### 1. **Startup Logging**
- Environment variables (DB_HOST, DB_NAME, DB_USER, PORT)
- Database connection pool initialization
- Database connection test with detailed error codes
- Route registration confirmation
- Server startup messages

### 2. **Request/Response Logging**
- Every incoming request (method, URL, IP, timestamp)
- Request body (first 200 chars)
- Authorization headers (first 20 chars)
- Response status codes
- Response timing

### 3. **Database Logging**
- Connection pool attempts
- Query execution (first 100 chars of query)
- Query parameters
- Query results (row count)
- Detailed error codes for connection failures:
  - `ECONNREFUSED` - MySQL server not running
  - `ER_ACCESS_DENIED_ERROR` - Wrong credentials
  - `ER_BAD_DB_ERROR` - Database doesn't exist

### 4. **Error Logging**
- Uncaught exceptions (with stack traces)
- Unhandled promise rejections
- Express error handler (with request details)
- 404 routes (route not found)
- Database query errors

---

## 🔍 Where to Find Logs on cPanel Hosting

### **Method 1: Node.js Application Logs** (Primary Location) ⭐

This is where your `console.log()` output goes:

1. **Login to cPanel**
2. **Navigate to:** `Software → Setup Node.js App`
3. **Find your application:** `back.v3.hpstockist.in`
4. **Click:** "Open Application"
5. **Click:** "Run NPM Install" (button at top)
6. **Look for:** "Log" or "View Application Log" button
7. **Alternative:** Check "Application log file path" field - usually shows something like:
   ```
   /home/earnmone/nodevenv/back.v3.hpstockist.in/12/logs/passenger.log
   ```

**Via File Manager:**
```
/home/earnmone/nodevenv/back.v3.hpstockist.in/[version]/logs/passenger.log
```

**Via SSH:**
```bash
# Find the log file
find /home/earnmone -name "passenger.log" -type f

# View live logs (tail)
tail -f /home/earnmone/nodevenv/back.v3.hpstockist.in/*/logs/passenger.log

# View last 100 lines
tail -n 100 /home/earnmone/nodevenv/back.v3.hpstockist.in/*/logs/passenger.log

# Search for errors
grep -i "error" /home/earnmone/nodevenv/back.v3.hpstockist.in/*/logs/passenger.log
```

---

### **Method 2: Apache/Passenger Error Logs**

This shows server-level errors (why Passenger couldn't start your app):

1. **cPanel → Metrics → Errors**
2. Look for recent entries related to your domain
3. Common location:
   ```
   /home/earnmone/logs/back.v3.hpstockist.in.error.log
   ```

**Via SSH:**
```bash
# View error log
tail -n 100 /home/earnmone/logs/back.v3.hpstockist.in.error.log

# Live monitoring
tail -f /home/earnmone/logs/back.v3.hpstockist.in.error.log

# Search for specific errors
grep -i "503\|crash\|fatal" /home/earnmone/logs/back.v3.hpstockist.in.error.log
```

---

### **Method 3: Access Logs**

Shows all HTTP requests (you've already seen this):

1. **cPanel → Metrics → Raw Access**
2. Download or view: `back.v3.hpstockist.in-access_log`
3. Location:
   ```
   /home/earnmone/logs/back.v3.hpstockist.in-access_log
   ```

---

### **Method 4: PM2 Logs** (If using PM2)

If you set up PM2 for process management:

```bash
pm2 logs
pm2 logs [app-name]
pm2 logs --lines 100
pm2 flush  # Clear logs
```

---

## 🎯 Quick Debug Commands (SSH)

### **1. Check if Node app is running**
```bash
ps aux | grep node
```

### **2. Check Node.js version**
```bash
node --version
```

### **3. Check if .env file exists**
```bash
ls -la /home/earnmone/back.v3.hpstockist.in/.env
cat /home/earnmone/back.v3.hpstockist.in/.env
```

### **4. Test database connection manually**
```bash
mysql -u earnmone_indi-vouch-new -p'Vision@21' -h localhost earnmone_indi-vouch-new
```

### **5. Check disk space**
```bash
df -h
```

### **6. Check memory usage**
```bash
free -m
```

### **7. View all logs at once**
```bash
# View application logs
tail -n 50 /home/earnmone/nodevenv/back.v3.hpstockist.in/*/logs/passenger.log

echo "=========================================="

# View error logs
tail -n 50 /home/earnmone/logs/back.v3.hpstockist.in.error.log
```

---

## 📊 What Logs Will Show Now

### **On Startup:**
```
╔═══════════════════════════════════════════════╗
║   INDI-VOUCH Backend Server Starting...      ║
╚═══════════════════════════════════════════════╝

🔧 Environment loaded: {
  PORT: 3000,
  DB_HOST: 'localhost',
  DB_NAME: 'earnmone_indi-vouch-new',
  DB_USER: 'earnmone_indi-vouch-new',
  NODE_ENV: 'development'
}

📊 Initializing MySQL connection pool...
   Host: localhost
   Database: earnmone_indi-vouch-new
   User: earnmone_indi-vouch-new
   Port: 3306

✅ All routes registered successfully

🚀 Starting server initialization...
📁 Working directory: /home/earnmone/back.v3.hpstockist.in
🔧 Node version: v18.x.x

🔌 Testing database connection...
🔍 testConnection() called...
   Requesting connection from pool...
   ✅ Connection acquired from pool
   Testing simple query...
   ✅ Query executed successfully
✅ Database connected successfully
📊 Connected to database: earnmone_indi-vouch-new
   Connection released back to pool
✅ Database connection successful

═══════════════════════════════════════════════
🚀 Server is running on port 3000
```

### **On Each Request:**
```
📥 [2025-11-03T06:27:14.123Z] GET /db-health
   IP: 36.50.162.196
🔍 DB Health check requested...
   Attempting database connection...
🔍 testConnection() called...
   Requesting connection from pool...
   ✅ Connection acquired from pool
   Testing simple query...
   ✅ Query executed successfully
✅ Database connected successfully
📊 Connected to database: earnmone_indi-vouch-new
   Connection released back to pool
   Connection result: true
✅ DB Health: Connected successfully
📤 [2025-11-03T06:27:14.123Z] GET /db-health - Status: 200
```

### **On Error:**
```
❌ Database connection failed
   Error code: ECONNREFUSED
   Error message: connect ECONNREFUSED 127.0.0.1:3306
   SQL State: undefined
   Error number: undefined
   >> MySQL server is not running or not accessible
```

or

```
❌ Database connection failed
   Error code: ER_ACCESS_DENIED_ERROR
   Error message: Access denied for user 'earnmone_indi-vouch-new'@'localhost'
   SQL State: 28000
   Error number: 1045
   >> Access denied - Check username and password
```

---

## 🚨 Common 503 Issues to Look For

Based on the logs you'll now see, check for:

1. **Missing .env file**
   ```
   DB_NAME: 'Not set'
   DB_USER: 'Not set'
   ```

2. **Wrong database credentials**
   ```
   ❌ Database connection failed
   Error code: ER_ACCESS_DENIED_ERROR
   >> Access denied - Check username and password
   ```

3. **Database doesn't exist**
   ```
   Error code: ER_BAD_DB_ERROR
   >> Database does not exist
   ```

4. **MySQL not running**
   ```
   Error code: ECONNREFUSED
   >> MySQL server is not running or not accessible
   ```

5. **Module not found**
   ```
   ❌ FATAL: Failed to start server
   Error: Cannot find module 'express'
   ```

6. **Port already in use**
   ```
   Error: listen EADDRINUSE: address already in use :::3000
   ```

---

## 🔄 After Making Changes

1. **Restart the Node app:**
   - cPanel → Setup Node.js App → **Restart** button

2. **Clear logs (optional):**
   ```bash
   > /home/earnmone/nodevenv/back.v3.hpstockist.in/*/logs/passenger.log
   ```

3. **Test immediately:**
   ```bash
   curl https://back.v3.hpstockist.in/health
   curl https://back.v3.hpstockist.in/db-health
   ```

4. **Check logs again:**
   ```bash
   tail -f /home/earnmone/nodevenv/back.v3.hpstockist.in/*/logs/passenger.log
   ```

---

## 📱 Next Steps

1. ✅ **Create `.env` file** with correct credentials (already provided)
2. ✅ **Restart Node.js application**
3. ✅ **Check logs** using methods above
4. ✅ **Test endpoints:**
   - `https://back.v3.hpstockist.in/health` (should work)
   - `https://back.v3.hpstockist.in/db-health` (should now work)
5. ✅ **Share log output** if still getting 503

---

## 💡 Pro Tips

- **Real-time monitoring:** Keep SSH terminal open with `tail -f` on log file
- **Log rotation:** cPanel automatically rotates logs, old ones might be compressed
- **Timestamps:** All logs now have ISO timestamps for easy debugging
- **Grep is your friend:** Use `grep`, `grep -A 5` (5 lines after), `grep -B 5` (5 lines before)

---

**The comprehensive logging will now show you exactly where the 503 error is coming from!** 🎯
