> ## Documentation Index
> Fetch the complete documentation index at: https://vij.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# GET /api/logs

> Retrieve error logs with filtering and pagination

The GET `/api/logs` endpoint retrieves stored error logs with support for filtering, searching, sorting, and pagination.

## Query Parameters

<ParamField query="severity" type="string">
  Filter by severity level.

  **Values**: `error`, `warning`, `info`

  **Example**: `/api/logs?severity=error`
</ParamField>

<ParamField query="environment" type="string">
  Filter by environment name.

  **Example**: `/api/logs?environment=production`
</ParamField>

<ParamField query="appId" type="string">
  Filter by application ID.

  **Example**: `/api/logs?appId=my-frontend-app`
</ParamField>

<ParamField query="search" type="string">
  Full-text search across message and stack fields.

  **Example**: `/api/logs?search=TypeError`
</ParamField>

<ParamField query="startDate" type="string">
  Filter logs created after this date (ISO 8601).

  **Example**: `/api/logs?startDate=2024-01-01T00:00:00Z`
</ParamField>

<ParamField query="endDate" type="string">
  Filter logs created before this date (ISO 8601).

  **Example**: `/api/logs?endDate=2024-01-31T23:59:59Z`
</ParamField>

<ParamField query="page" type="number" default="1">
  Page number for pagination (1-indexed).

  **Example**: `/api/logs?page=2`
</ParamField>

<ParamField query="limit" type="number" default="50">
  Number of results per page (max: 100).

  **Example**: `/api/logs?limit=100`
</ParamField>

<ParamField query="sortBy" type="string" default="timestamp">
  Field to sort by.

  **Values**: `timestamp`, `severity`, `appId`, `environment`

  **Example**: `/api/logs?sortBy=severity`
</ParamField>

<ParamField query="sortOrder" type="string" default="desc">
  Sort order.

  **Values**: `asc` (ascending), `desc` (descending)

  **Example**: `/api/logs?sortOrder=asc`
</ParamField>

<ParamField query="group" type="string">
  Filter by error group fingerprint.

  **Example**: `/api/logs?group=abc123def456`
</ParamField>

## Response Fields

<ResponseField name="logs" type="array">
  Array of error log objects.

  <Expandable title="Log object properties">
    <ResponseField name="_id" type="string">
      MongoDB ObjectId of the log entry.
    </ResponseField>

    <ResponseField name="message" type="string">
      Error message.
    </ResponseField>

    <ResponseField name="name" type="string">
      Error name/type.
    </ResponseField>

    <ResponseField name="stack" type="string">
      Stack trace.
    </ResponseField>

    <ResponseField name="severity" type="string">
      Severity level: `error`, `warning`, or `info`.
    </ResponseField>

    <ResponseField name="timestamp" type="string">
      ISO 8601 timestamp when error occurred.
    </ResponseField>

    <ResponseField name="appId" type="string">
      Application identifier.
    </ResponseField>

    <ResponseField name="environment" type="string">
      Environment name.
    </ResponseField>

    <ResponseField name="metadata" type="object">
      Custom metadata attached to the error.
    </ResponseField>

    <ResponseField name="context" type="object">
      Browser or Node.js context information.
    </ResponseField>

    <ResponseField name="group" type="string">
      Error group fingerprint for deduplication.
    </ResponseField>

    <ResponseField name="aiAnalysis" type="object">
      AI-generated analysis (if available).

      <Expandable title="AI analysis properties">
        <ResponseField name="summary" type="string">
          Concise error summary.
        </ResponseField>

        <ResponseField name="possibleCause" type="string">
          Root cause analysis.
        </ResponseField>

        <ResponseField name="suggestedFix" type="string">
          Recommended fix suggestions.
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="total" type="number">
  Total number of logs matching the query.
</ResponseField>

<ResponseField name="page" type="number">
  Current page number.
</ResponseField>

<ResponseField name="limit" type="number">
  Results per page.
</ResponseField>

<ResponseField name="pages" type="number">
  Total number of pages.
</ResponseField>

## Example Requests

<CodeGroup>
  ```bash Get All Errors theme={null}
  curl "https://vij.example.com/api/logs?severity=error"
  ```

  ```bash Filter by Environment theme={null}
  curl "https://vij.example.com/api/logs?environment=production&severity=error"
  ```

  ```bash Search and Filter theme={null}
  curl "https://vij.example.com/api/logs?search=TypeError&appId=my-app&limit=10"
  ```

  ```bash Date Range theme={null}
  curl "https://vij.example.com/api/logs?startDate=2024-01-01T00:00:00Z&endDate=2024-01-31T23:59:59Z"
  ```

  ```bash Pagination theme={null}
  curl "https://vij.example.com/api/logs?page=2&limit=50&sortBy=timestamp&sortOrder=desc"
  ```
</CodeGroup>

## Example Response

<ResponseExample>
  ```json Success (200) theme={null}
  {
    "logs": [
      {
        "_id": "65a1b2c3d4e5f6g7h8i9j0k1",
        "message": "Payment processing failed",
        "name": "Error",
        "stack": "Error: Payment processing failed\n    at processPayment (payment.js:45:12)\n    at handleCheckout (checkout.js:123:5)",
        "severity": "error",
        "timestamp": "2024-01-01T12:34:56.789Z",
        "appId": "my-frontend-app",
        "environment": "production",
        "metadata": {
          "userId": "user-123",
          "orderId": "order-456",
          "feature": "checkout"
        },
        "context": {
          "viewport": { "width": 1920, "height": 1080 },
          "browser": {
            "userAgent": "Mozilla/5.0...",
            "language": "en-US"
          }
        },
        "group": "abc123def456",
        "aiAnalysis": {
          "summary": "Payment object was undefined when processing transaction",
          "possibleCause": "API request failed or user session expired",
          "suggestedFix": "Add null check before accessing payment.amount"
        }
      },
      {
        "_id": "65a1b2c3d4e5f6g7h8i9j0k2",
        "message": "Database connection timeout",
        "name": "TimeoutError",
        "stack": "TimeoutError: Connection timeout\n    at connect (db.js:23:10)",
        "severity": "error",
        "timestamp": "2024-01-01T12:30:00.000Z",
        "appId": "backend-api",
        "environment": "production",
        "metadata": {
          "database": "mongodb",
          "timeout": 5000
        },
        "context": {
          "process": {
            "pid": 12345,
            "platform": "linux",
            "nodeVersion": "v20.0.0"
          }
        },
        "group": "def456ghi789"
      }
    ],
    "total": 1547,
    "page": 1,
    "limit": 50,
    "pages": 31
  }
  ```
</ResponseExample>

## Error Responses

<ResponseExample>
  ```json Bad Request (400) theme={null}
  {
    "error": "Invalid severity value. Must be 'error', 'warning', or 'info'"
  }
  ```

  ```json Invalid Date Format (400) theme={null}
  {
    "error": "Invalid date format for startDate. Use ISO 8601 format"
  }
  ```

  ```json Server Error (500) theme={null}
  {
    "error": "Failed to fetch logs"
  }
  ```
</ResponseExample>

## Filtering Examples

### By Severity

```bash theme={null}
# Get only errors
GET /api/logs?severity=error

# Get warnings and info
GET /api/logs?severity=warning
GET /api/logs?severity=info
```

### By Environment

```bash theme={null}
# Production errors only
GET /api/logs?environment=production&severity=error

# Staging errors
GET /api/logs?environment=staging&severity=error
```

### By Application

```bash theme={null}
# Specific app
GET /api/logs?appId=my-frontend-app

# Multiple apps (requires multiple queries or custom implementation)
GET /api/logs?appId=my-frontend-app
GET /api/logs?appId=my-backend-app
```

### By Date Range

```bash theme={null}
# Last 24 hours
GET /api/logs?startDate=$(date -u -d '1 day ago' +%Y-%m-%dT%H:%M:%SZ)

# Specific month
GET /api/logs?startDate=2024-01-01T00:00:00Z&endDate=2024-01-31T23:59:59Z

# Today's errors
GET /api/logs?startDate=$(date -u +%Y-%m-%dT00:00:00Z)
```

### Full-Text Search

```bash theme={null}
# Search for specific error
GET /api/logs?search=TypeError

# Search in specific app
GET /api/logs?search=payment&appId=my-app

# Search with phrase
GET /api/logs?search="cannot%20read%20property"
```

### Combined Filters

```bash theme={null}
# Complex query
GET /api/logs?severity=error&environment=production&appId=my-app&search=payment&startDate=2024-01-01T00:00:00Z&limit=25
```

## Pagination

Navigate through large result sets:

```bash theme={null}
# First page
GET /api/logs?page=1&limit=50

# Second page
GET /api/logs?page=2&limit=50

# Large page size
GET /api/logs?page=1&limit=100  # Max: 100
```

**Response includes**:

* `total` - Total matching logs
* `page` - Current page
* `limit` - Items per page
* `pages` - Total pages

**Calculate next page**:

```javascript theme={null}
if (page < pages) {
  const nextPage = page + 1;
  fetch(`/api/logs?page=${nextPage}&limit=${limit}`);
}
```

## Sorting

Sort results by different fields:

```bash theme={null}
# Newest first (default)
GET /api/logs?sortBy=timestamp&sortOrder=desc

# Oldest first
GET /api/logs?sortBy=timestamp&sortOrder=asc

# Sort by severity
GET /api/logs?sortBy=severity&sortOrder=desc

# Sort by app
GET /api/logs?sortBy=appId&sortOrder=asc
```

## Performance Considerations

<AccordionGroup>
  <Accordion title="Use time filters">
    Always include time filters to reduce query scope:

    ```bash theme={null}
    # Good - scans less data
    GET /api/logs?startDate=2024-01-01T00:00:00Z

    # Slow - scans all data
    GET /api/logs
    ```
  </Accordion>

  <Accordion title="Limit page size">
    Use reasonable page sizes:

    ```bash theme={null}
    # Good
    GET /api/logs?limit=50

    # Slow
    GET /api/logs?limit=10000
    ```

    Maximum allowed: 100 items per page
  </Accordion>

  <Accordion title="Use indexed fields">
    These fields are indexed for fast queries:

    * `timestamp`
    * `severity`
    * `environment`
    * `appId`
    * `group`

    Metadata fields are not indexed by default.
  </Accordion>

  <Accordion title="Text search performance">
    Full-text search uses MongoDB text index:

    ```bash theme={null}
    # Fast (indexed)
    GET /api/logs?search=TypeError

    # Slower on large datasets
    GET /api/logs?search=very%20specific%20long%20phrase
    ```
  </Accordion>
</AccordionGroup>

## Client Implementation

### JavaScript/TypeScript

```typescript theme={null}
interface LogQuery {
  severity?: 'error' | 'warning' | 'info';
  environment?: string;
  appId?: string;
  search?: string;
  startDate?: string;
  endDate?: string;
  page?: number;
  limit?: number;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

async function fetchLogs(query: LogQuery) {
  const params = new URLSearchParams(
    Object.entries(query)
      .filter(([_, v]) => v !== undefined)
      .map(([k, v]) => [k, String(v)])
  );

  const response = await fetch(
    `https://vij.example.com/api/logs?${params}`
  );

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  }

  return response.json();
}

// Usage
const logs = await fetchLogs({
  severity: 'error',
  environment: 'production',
  page: 1,
  limit: 50
});
```

### Python

```python theme={null}
import requests
from typing import Optional, Literal

def fetch_logs(
    severity: Optional[Literal['error', 'warning', 'info']] = None,
    environment: Optional[str] = None,
    app_id: Optional[str] = None,
    search: Optional[str] = None,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    page: int = 1,
    limit: int = 50
):
    params = {
        k: v for k, v in {
            'severity': severity,
            'environment': environment,
            'appId': app_id,
            'search': search,
            'startDate': start_date,
            'endDate': end_date,
            'page': page,
            'limit': limit
        }.items() if v is not None
    }

    response = requests.get(
        'https://vij.example.com/api/logs',
        params=params
    )

    response.raise_for_status()
    return response.json()

# Usage
logs = fetch_logs(
    severity='error',
    environment='production',
    page=1,
    limit=50
)
```

## Rate Limiting

<Note>
  No rate limiting by default. Implement rate limiting in production.
</Note>

**Recommended limits**:

* 100 requests per minute per IP
* 1,000 requests per hour per user

## Caching

Responses can be cached for performance:

```bash theme={null}
# Cache-Control header
Cache-Control: public, max-age=60
```

**Cache key should include**:

* All query parameters
* Current time bucket (e.g., minute)

## Related Endpoints

<CardGroup cols={2}>
  <Card title="POST /api/logs" icon="upload" href="/api-reference/logs/post">
    Send error logs to VIJ
  </Card>

  <Card title="GET /api/stats" icon="chart-bar" href="/api-reference/stats">
    Get error statistics
  </Card>

  <Card title="GET /api/groups" icon="layer-group" href="/api-reference/groups">
    Retrieve error groups
  </Card>

  <Card title="Filtering Guide" icon="filter" href="/advanced/filtering-and-search">
    Advanced filtering techniques
  </Card>
</CardGroup>
