npm package: @radai/logger
Description: A structured logging solution for RadAI TypeScript services with OpenTelemetry integration.
Latest version: 0.0.1

# @radai/logger

A structured logging solution for RadAI TypeScript services with OpenTelemetry integration.

## Features

- **Environment-aware**: Automatically routes logs to the correct environment endpoints
- **OpenTelemetry Integration**: Enhances logs with tracing information and supports multiple transport protocols
- **Structured Logging**: All logs are structured JSON with metadata
- **Pretty Printing**: Developer-friendly output in development mode
- **Module Loggers**: Create child loggers for specific modules
- **Type-safe**: Full TypeScript support

## Installation

```bash
npm install @radai/logger
```

## Usage

### Basic Logging

```typescript
import { createRadaiLogger } from '@radai/logger';

const logger = createRadaiLogger({
  appName: 'my-service',
  environment: process.env.NODE_ENV || 'development'
});

logger.info('Application started');
logger.error({ error: new Error('Something went wrong') }, 'Operation failed');
```

### Module-Specific Logging

```typescript
import { createModuleLogger } from '@radai/logger';

const userLogger = createModuleLogger('user-service', {
  appName: 'my-service',
  environment: 'development'
});

userLogger.info({ userId: '123' }, 'User profile updated');
```

### OpenTelemetry Integration

The logger automatically configures OpenTelemetry with multiple transport protocols:

```typescript
import { createRadaiLogger } from '@radai/logger';

const logger = createRadaiLogger({
  appName: 'my-service',
  environment: 'production',
  enableOtel: true,
  version: '1.0.0'
});

// Logs will be sent to:
// 1. HTTP endpoint (default)
// 2. gRPC endpoint with auth headers
// 3. Console output (in development)
logger.info('Service health check');
```

### Express Integration

```typescript
import express from 'express';
import { createRadaiLogger } from '@radai/logger';

const app = express();
const logger = createRadaiLogger({
  appName: 'api-service',
  environment: 'production'
});

app.use((req, res, next) => {
  logger.info(
    {
      method: req.method,
      path: req.path,
      query: req.query
    },
    'Incoming request'
  );
  next();
});
```

## Configuration

The logger can be configured using the following options:

```typescript
interface RadaiLoggerOptions {
  appName: string;
  environment: 'development' | 'staging' | 'production';
  level?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
  version?: string;
  orgId?: string;
  authToken?: string;
  loggingEndpoint?: string;
  requestTimeout?: number;
  enableOtel?: boolean;
}
```

### Environment Variables

The logger can be configured using the following environment variables:

- `NODE_ENV`: Environment ('development', 'staging', 'production')
- `APP_NAME`: Application name
- `RADGINX_AUTH_TOKEN`: Authentication token for RadGINX
- `ORG_ID`: Organization ID
- `LOG_LEVEL`: Minimum log level
- `REQUEST_TIMEOUT`: Timeout for requests to RadGINX
- `ENABLE_OTEL`: Enable OpenTelemetry integration
- `LOGGING_ENDPOINT`: Custom logging endpoint
- `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`: OpenTelemetry collector endpoint for logs
- `OTEL_RESOURCE_ATTRIBUTES`: OpenTelemetry resource attributes

### OpenTelemetry Configuration

The logger uses pino-opentelemetry-transport with the following configuration:

- HTTP transport for general logging
- gRPC transport with auth headers for secure logging
- Console transport for local development
- Automatic service name and version tracking
- Error handling and ready event monitoring

## API Reference

### Main Exports

- `createRadaiLogger(options)`: Create a configured logger
- `createChildLogger(context, parent)`: Create a child logger with additional context
- `createModuleLogger(moduleName, context, parent)`: Create a module-specific logger
- `sendLogsToServer(logData, options)`: Send logs to RadGINX
- `logError(logger, error, message)`: Helper for properly logging errors

## Best Practices

1. **Use consistent configuration**: Configure your application to use the same logger throughout

2. **Create module loggers**: Add context to your logs with module-specific loggers

3. **Structured logging**: Use objects for log context instead of string concatenation

   ```typescript
   // Good
   logger.info({ userId, action }, 'User performed action');

   // Avoid
   logger.info(`User ${userId} performed ${action}`);
   ```

4. **Error logging**: Use the `logError` helper to properly capture error details
   ```typescript
   try {
     // Operation
   } catch (error) {
     logError(logger, error, 'Operation failed');
   }
   ```

5. **Version tracking**: Always specify your service version for better observability
   ```typescript
   const logger = createRadaiLogger({
     appName: 'my-service',
     version: '1.0.0'
   });
   ```