Skip to main content

Class: MaximLogger

Defined in: src/lib/logger/logger.ts:39 Main logger class for the Maxim SDK providing comprehensive observability capabilities. Manages the entire lifecycle of capturing, storing, and sending logs to the Maxim backend. Supports distributed logging and provides methods for logging sessions, traces, generations, tool calls, retrievals, and other observability events. Essential for monitoring AI applications and understanding system behavior. MaximLogger

Example

import { Maxim } from '@maximai/maxim-js';

// Create logger through Maxim instance
const maxim = new Maxim({ apiKey: 'your-api-key' });
const logger = await maxim.logger({ id: 'my-app' });

Constructors

Constructor

new MaximLogger(params): MaximLogger
Defined in: src/lib/logger/logger.ts:65 Creates a new MaximLogger instance.

Parameters

params
Configuration parameters for the logger
apiKey
string API key for authenticating with Maxim backend
baseUrl
string Base URL for the Maxim API
cache
MaximCache Cache implementation for distributed logging
config
LoggerConfig Logger configuration including ID and flush settings
isDebug?
boolean Enable debug mode for additional logging
raiseExceptions
boolean Whether to raise exceptions or log them

Returns

MaximLogger

Throws

When logger ID is not provided in the configuration

Example

// Usually created through Maxim.logger() method
const logger = new MaximLogger({
  config: { id: 'my-app', autoFlush: true },
  apiKey: 'your-api-key',
  baseUrl: 'https://app.getmaxim.ai',
  cache: new MaximInMemoryCache(),
  raiseExceptions: false
});

Accessors

id

Get Signature

get id(): string
Defined in: src/lib/logger/logger.ts:145 Gets the unique identifier for this logger instance.
Returns
string The logger’s unique ID

Methods

cleanup()

cleanup(): Promise<void>
Defined in: src/lib/logger/logger.ts:164 Cleans up resources and ensures all pending logs are flushed. Should be called before application shutdown to ensure no logs are lost. Waits for all pending write operations to complete.

Returns

Promise<void> Promise that resolves when cleanup is complete

Async

Example

// Cleanup before app shutdown
process.on('SIGTERM', async () => {
  await logger.cleanup();
  process.exit(0);
});

flush()

flush(): void
Defined in: src/lib/logger/logger.ts:998 Flushes all pending logs to the backend immediately. Forces the log writer to send all queued logs to the Maxim backend without waiting for the automatic flush interval.

Returns

void void

Example

// Force flush before critical operation
logger.flush();

generationAddMessage()

generationAddMessage(generationId, messages): void
Defined in: src/lib/logger/logger.ts:532 Adds additional messages to a generation’s conversation.

Parameters

generationId
string The unique identifier of the generation
messages
(ChatCompletionMessage | CompletionRequest)[] Array of messages to add

Returns

void void

Example

logger.generationAddMessage('gen-123', [
  { role: 'user', content: 'Can you clarify that?' }
]);

generationAddTag()

generationAddTag(generationId, key, value): void
Defined in: src/lib/logger/logger.ts:517 Adds a tag to a generation for categorization and filtering.

Parameters

generationId
string The unique identifier of the generation
key
string The tag key
value
string The tag value

Returns

void void

Example

logger.generationAddTag('gen-123', 'type', 'chat_completion');
logger.generationAddTag('gen-123', 'use_case', 'customer_support');

generationEnd()

generationEnd(generationId, data?): void
Defined in: src/lib/logger/logger.ts:634 Ends a generation and records the end timestamp.

Parameters

generationId
string The unique identifier of the generation
data?
any

Returns

void void

Example

logger.generationEnd('gen-123');

generationError()

generationError(generationId, error): void
Defined in: src/lib/logger/logger.ts:591 Records an error that occurred during a generation.

Parameters

generationId
string The unique identifier of the generation
error
GenerationError Error information including message, code, and type

Returns

void void

Example

logger.generationError('gen-123', {
  message: 'API request timed out',
  code: 'TIMEOUT_ERROR',
  type: 'NetworkError'
});

generationEvaluate()

generationEvaluate(generationId): EvaluateContainer
Defined in: src/lib/logger/logger.ts:622 Gets the evaluation methods for a generation.

Parameters

generationId
string The unique identifier of the generation

Returns

EvaluateContainer Evaluation methods for configuring and triggering evaluations on the generation

Example

logger.generationEvaluate('gen-123')
  .withEvaluators('bias', 'toxicity')
  .withVariables({ expected_output: 'The correct answer' });

generationMetadata()

generationMetadata(generationId, metadata): void
Defined in: src/lib/logger/logger.ts:608 Adds metadata to a generation for additional context and debugging.

Parameters

generationId
string The unique identifier of the generation
metadata
Record<string, unknown> Key-value pairs of metadata

Returns

void void

Example

logger.generationMetadata('gen-123', {
  requestId: 'req-789',
  latency: 1200,
  tokensPerSecond: 15.5
});

generationResult()

generationResult(generationId, result): void
Defined in: src/lib/logger/logger.ts:574 Records the successful result of a generation and ends it.

Parameters

generationId
string The unique identifier of the generation
result
The completion result from the LLM ChatCompletionResult | TextCompletionResult

Returns

void void

Example

logger.generationResult('gen-123', {
  id: 'cmpl-456',
  object: 'chat.completion',
  created: Date.now(),
  model: 'gpt-4',
  choices: [{
    index: 0,
    message: { role: 'assistant', content: 'Hello! How can I help?' },
    finish_reason: 'stop',
    logprobs: null
  }],
  usage: { prompt_tokens: 10, completion_tokens: 8, total_tokens: 18 }
});

generationSetModel()

generationSetModel(generationId, model): void
Defined in: src/lib/logger/logger.ts:502 Updates the model being used for a generation.

Parameters

generationId
string The unique identifier of the generation
model
string The new model name or identifier

Returns

void void

Example

logger.generationSetModel('gen-123', 'gpt-4-turbo');

generationSetModelParameters()

generationSetModelParameters(generationId, modelParameters): void
Defined in: src/lib/logger/logger.ts:549 Updates the model parameters for a generation.

Parameters

generationId
string The unique identifier of the generation
modelParameters
Record<string, any> Object containing model-specific parameters

Returns

void void

Example

logger.generationSetModelParameters('gen-123', {
  temperature: 0.9,
  max_tokens: 500,
  top_p: 0.95
});

retrievalAddTag()

retrievalAddTag(retrievalId, key, value): void
Defined in: src/lib/logger/logger.ts:850 Adds a tag to a retrieval for categorization and filtering.

Parameters

retrievalId
string The unique identifier of the retrieval
key
string The tag key
value
string The tag value

Returns

void void

Example

logger.retrievalAddTag('retrieval-123', 'source', 'knowledge_base');
logger.retrievalAddTag('retrieval-123', 'query_type', 'semantic');

retrievalEnd()

retrievalEnd(retrievalId): void
Defined in: src/lib/logger/logger.ts:835 Ends a retrieval and records the end timestamp.

Parameters

retrievalId
string The unique identifier of the retrieval

Returns

void void

Example

logger.retrievalEnd('retrieval-123');

retrievalEvaluate()

retrievalEvaluate(retrievalId): EvaluateContainer
Defined in: src/lib/logger/logger.ts:915 Gets the evaluation methods for a retrieval.

Parameters

retrievalId
string The unique identifier of the retrieval

Returns

EvaluateContainer Evaluation methods for configuring and triggering evaluations on the retrieval

Example

logger.retrievalEvaluate('retrieval-123')
  .withEvaluators('relevance', 'recall')
  .withVariables({ context: 'user_query', expected: 'ground_truth' });

retrievalInput()

retrievalInput(retrievalId, input): void
Defined in: src/lib/logger/logger.ts:863 Sets the input query for a retrieval operation.

Parameters

retrievalId
string The unique identifier of the retrieval
input
string The search query or input text

Returns

void void

Example

logger.retrievalInput('retrieval-123', 'How do I troubleshoot network issues?');

retrievalMetadata()

retrievalMetadata(retrievalId, metadata): void
Defined in: src/lib/logger/logger.ts:901 Adds metadata to a retrieval for additional context and debugging.

Parameters

retrievalId
string The unique identifier of the retrieval
metadata
Record<string, unknown> Key-value pairs of metadata

Returns

void void

Example

logger.retrievalMetadata('retrieval-123', {
  searchTime: 150,
  resultsCount: 5,
  similarityThreshold: 0.85
});

retrievalOutput()

retrievalOutput(retrievalId, output): void
Defined in: src/lib/logger/logger.ts:884 Sets the output results for a retrieval operation and ends it.

Parameters

retrievalId
string The unique identifier of the retrieval
output
string Retrieved documents as a single string or array

Returns

void void

Examples

// Single result
logger.retrievalOutput('retrieval-123', 'Network troubleshooting guide: First, check cables...');
// Multiple results
logger.retrievalOutput('retrieval-123', [
  'Document 1: Basic troubleshooting steps...',
  'Document 2: Advanced network diagnostics...'
]);

session()

session(config): Session
Defined in: src/lib/logger/logger.ts:110 Creates a new session. Sessions represent high-level mutli-turn user interactions, containing multiple traces that represent individual turn interaction within that session. Useful for tracking user journeys.

Parameters

config
SessionConfig Configuration for the session

Returns

Session A new session instance for logging activities

Example

const session = logger.session({
  id: 'user-session-123',
  name: 'Customer Support Chat',
});

// Add feedback to the session
session.feedback({ score: 5, comment: 'Very helpful!' });
session.end();

sessionEnd()

sessionEnd(sessionId, data?): void
Defined in: src/lib/logger/logger.ts:193 Ends a session and records the end timestamp.

Parameters

sessionId
string The unique identifier of the session
data?
any

Returns

void void

Example

logger.sessionEnd('session-123');

sessionEvaluate()

sessionEvaluate(sessionId): EvaluateContainer
Defined in: src/lib/logger/logger.ts:241 Gets the evaluation methods for a session.

Parameters

sessionId
string The unique identifier of the session

Returns

EvaluateContainer Evaluation methods for configuring and triggering evaluations on the session

Example

logger.sessionEvaluate('session-123')
  .withEvaluators('bias', 'toxicity')
  .withVariables({ context: 'session_context' });

sessionFeedback()

sessionFeedback(sessionId, feedback): void
Defined in: src/lib/logger/logger.ts:211 Adds feedback to a session from users.

Parameters

sessionId
string The unique identifier of the session
feedback
Feedback object containing score and optional comment
comment?
string Optional textual feedback
score
number Numerical score for the session

Returns

void void

Example

logger.sessionFeedback('session-123', {
  score: 5,
  comment: 'Excellent customer service!'
});

sessionTag()

sessionTag(sessionId, key, value): void
Defined in: src/lib/logger/logger.ts:181 Adds a tag to a session for categorization and filtering.

Parameters

sessionId
string The unique identifier of the session
key
string The tag key
value
string The tag value

Returns

void void

Example

logger.sessionTag('session-123', 'environment', 'production');
logger.sessionTag('session-123', 'user_type', 'premium');

sessionTrace()

sessionTrace(sessionId, config): Trace
Defined in: src/lib/logger/logger.ts:227 Creates a new trace associated with a session.

Parameters

sessionId
string The unique identifier of the session
config
TraceConfig Configuration for the new trace

Returns

Trace A new trace instance associated with the session

Example

const trace = logger.sessionTrace('session-123', {
  id: 'query-trace-001',
  name: 'User Query Processing'
});

spanEnd()

spanEnd(spanId, data?): void
Defined in: src/lib/logger/logger.ts:821 Ends a span and records the end timestamp.

Parameters

spanId
string The unique identifier of the span
data?
any

Returns

void void

Example

logger.spanEnd('span-123');

spanError()

spanError(spanId, config): Error
Defined in: src/lib/logger/logger.ts:738 Creates an error associated with a span.

Parameters

spanId
string The unique identifier of the span
config
ErrorConfig Configuration for the error

Returns

Error A new error instance associated with the span

Example

const error = logger.spanError('span-123', {
  id: 'error-001',
  message: 'Validation failed',
  code: 'VALIDATION_ERROR',
  type: 'ValidationError'
});

spanEvaluate()

spanEvaluate(spanId): EvaluateContainer
Defined in: src/lib/logger/logger.ts:809 Gets the evaluation methods for a span.

Parameters

spanId
string The unique identifier of the span

Returns

EvaluateContainer Evaluation methods for configuring and triggering evaluations on the span

Example

logger.spanEvaluate('span-123')
  .withEvaluators('performance', 'accuracy')
  .withVariables({ expected_output: 'target_result' });

spanEvent()

Call Signature

spanEvent(spanId, eventId, eventName, tags?, metadata?): void
Defined in: src/lib/logger/logger.ts:760 Emits a custom event within a span.
Parameters
spanId
string The unique identifier of the span
eventId
string Unique identifier for the event
eventName
string Human-readable name for the event
tags?
Record<string, string> Optional tags for categorizing the event
metadata?
Record<string, unknown> Optional metadata for additional context
Returns
void void
Example
logger.spanEvent(
  'span-123',
  'validation-complete',
  'Data Validation Complete',
  { status: 'success', records: '1000' },
  { validationTime: 250, errorsFound: 0 }
);

Call Signature

spanEvent(spanId, eventName, tags?, metadata?): void
Defined in: src/lib/logger/logger.ts:768
Parameters
spanId
string
eventName
string
tags?
Record<string, string>
metadata?
Record<string, unknown>
Returns
void
Deprecated
Use the method with explicit eventId and eventName instead

spanGeneration()

spanGeneration(spanId, config): Generation
Defined in: src/lib/logger/logger.ts:655 Creates a new generation (LLM call) associated with a span.

Parameters

spanId
string The unique identifier of the span
config
GenerationConfig Configuration for the generation

Returns

Generation A new generation instance associated with the span

Example

const generation = logger.spanGeneration('span-123', {
  id: 'gen-001',
  provider: 'openai',
  model: 'gpt-4',
  messages: [{ role: 'user', content: 'Process this data' }],
  modelParameters: { temperature: 0.1 }
});

spanMetadata()

spanMetadata(spanId, metadata): void
Defined in: src/lib/logger/logger.ts:795 Adds metadata to a span for additional context and debugging.

Parameters

spanId
string The unique identifier of the span
metadata
Record<string, unknown> Key-value pairs of metadata

Returns

void void

Example

logger.spanMetadata('span-123', {
  processingTime: 500,
  itemsProcessed: 250,
  memoryUsage: '128MB'
});

spanRetrieval()

spanRetrieval(spanId, config): Retrieval
Defined in: src/lib/logger/logger.ts:671 Creates a new retrieval associated with a span.

Parameters

spanId
string The unique identifier of the span
config
RetrievalConfig Configuration for the retrieval

Returns

Retrieval A new retrieval instance associated with the span

Example

const retrieval = logger.spanRetrieval('span-123', {
  id: 'retrieval-001',
  name: 'Context Database Lookup'
});

spanSpan()

spanSpan(spanId, config): Span
Defined in: src/lib/logger/logger.ts:705 Creates a nested span within a span for hierarchical organization.

Parameters

spanId
string The unique identifier of the parent span
config
SpanConfig Configuration for the nested span

Returns

Span A new nested span instance

Example

const childSpan = logger.spanSpan('span-123', {
  id: 'child-span-001',
  name: 'Data Validation Step'
});

spanTag()

spanTag(spanId, key, value): void
Defined in: src/lib/logger/logger.ts:720 Adds a tag to a span for categorization and filtering.

Parameters

spanId
string The unique identifier of the span
key
string The tag key
value
string The tag value

Returns

void void

Example

logger.spanTag('span-123', 'phase', 'preprocessing');
logger.spanTag('span-123', 'status', 'in_progress');

spanToolCall()

spanToolCall(spanId, config): ToolCall
Defined in: src/lib/logger/logger.ts:689 Creates a new tool call associated with a span.

Parameters

spanId
string The unique identifier of the span
config
ToolCallConfig Configuration for the tool call

Returns

ToolCall A new tool call instance associated with the span

Example

const toolCall = logger.spanToolCall('span-123', {
  id: 'tool-001',
  name: 'api_call',
  description: 'Fetch data from external service',
  args: JSON.stringify({ endpoint: '/users', id: 123 })
});

toolCallAddTag()

toolCallAddTag(toolCallId, key, value): void
Defined in: src/lib/logger/logger.ts:966 Adds a tag to a tool call for categorization and filtering.

Parameters

toolCallId
string The unique identifier of the tool call
key
string The tag key
value
string The tag value

Returns

void void

Example

logger.toolCallAddTag('tool-123', 'category', 'database');
logger.toolCallAddTag('tool-123', 'priority', 'high');

toolCallError()

toolCallError(toolCallId, error): void
Defined in: src/lib/logger/logger.ts:951 Records an error that occurred during a tool call and ends it.

Parameters

toolCallId
string The unique identifier of the tool call
error
ToolCallError Error information including message, code, and type

Returns

void void

Example

logger.toolCallError('tool-123', {
  message: 'Database connection failed',
  code: 'DB_CONNECTION_ERROR',
  type: 'DatabaseError'
});

toolCallMetadata()

toolCallMetadata(toolCallId, metadata): void
Defined in: src/lib/logger/logger.ts:983 Adds metadata to a tool call for additional context and debugging.

Parameters

toolCallId
string The unique identifier of the tool call
metadata
Record<string, unknown> Key-value pairs of metadata

Returns

void void

Example

logger.toolCallMetadata('tool-123', {
  executionTime: 350,
  apiEndpoint: '/api/v1/users',
  responseSize: 1024
});

toolCallResult()

toolCallResult(toolCallId, result): void
Defined in: src/lib/logger/logger.ts:934 Records the successful result of a tool call and ends it.

Parameters

toolCallId
string The unique identifier of the tool call
result
string The result returned by the tool as a string

Returns

void void

Example

logger.toolCallResult('tool-123', JSON.stringify({
  userId: '12345',
  name: 'John Doe',
  email: '[email protected]'
}));

trace()

trace(config): Trace
Defined in: src/lib/logger/logger.ts:136 Creates a new trace. Traces represent individual workflows or processes, containing generations, tool calls, retrievals, and other components. They provide detailed information about operations in a single conversation turn with the user.

Parameters

config
TraceConfig Configuration for the trace

Returns

Trace A new trace instance for logging operations

Example

const trace = logger.trace({
  id: 'query-trace-456',
  name: 'Document Analysis',
});

// Add input and output to the trace
trace.input('Analyze this contract document');
// ...Log other operations
trace.output('Contract analysis complete: 3 issues found');
trace.end();

traceAddToSession()

traceAddToSession(traceId, sessionId): void
Defined in: src/lib/logger/logger.ts:369 Associates a trace with a session.

Parameters

traceId
string The unique identifier of the trace
sessionId
string The unique identifier of the session

Returns

void void

Example

logger.traceAddToSession('trace-123', 'session-456');

traceEnd()

traceEnd(traceId, data?): void
Defined in: src/lib/logger/logger.ts:487 Ends a trace and records the end timestamp.

Parameters

traceId
string The unique identifier of the trace
data?
any

Returns

void void

Example

logger.traceEnd('trace-123');

traceError()

traceError(traceId, config): Error
Defined in: src/lib/logger/logger.ts:327 Creates an error associated with a trace.

Parameters

traceId
string The unique identifier of the trace
config
ErrorConfig Configuration for the error

Returns

Error A new error instance associated with the trace

Example

const error = logger.traceError('trace-123', {
  id: 'error-001',
  message: 'Failed to process request',
  code: 'PROCESSING_ERROR',
  type: 'ProcessingError'
});

traceEvaluate()

traceEvaluate(traceId): EvaluateContainer
Defined in: src/lib/logger/logger.ts:475 Gets the evaluation methods for a trace.

Parameters

traceId
string The unique identifier of the trace

Returns

EvaluateContainer Evaluation methods for configuring and triggering evaluations on the trace

Example

logger.traceEvaluate('trace-123')
  .withEvaluators('bias', 'toxicity')
  .withVariables({ context: 'user_query', expected: 'gold_standard' });

traceEvent()

Call Signature

traceEvent(traceId, eventId, eventName, tags?, metadata?): void
Defined in: src/lib/logger/logger.ts:406 Emits a custom event within a trace.
Parameters
traceId
string The unique identifier of the trace
eventId
string Unique identifier for the event
eventName
string Human-readable name for the event
tags?
Record<string, string> Optional tags for categorizing the event
metadata?
Record<string, unknown> Optional metadata for additional context
Returns
void void
Example
logger.traceEvent(
  'trace-123',
  'checkpoint-1',
  'Processing Milestone',
  { phase: 'preprocessing', status: 'complete' },
  { itemsProcessed: 1000, timeElapsed: 5.2 }
);

Call Signature

traceEvent(traceId, eventName, tags?, metadata?): void
Defined in: src/lib/logger/logger.ts:414
Parameters
traceId
string
eventName
string
tags?
Record<string, string>
metadata?
Record<string, unknown>
Returns
void
Deprecated
Use the method with explicit eventId and eventName instead

traceFeedback()

traceFeedback(traceId, feedback): void
Defined in: src/lib/logger/logger.ts:444 Adds feedback to a trace from users.

Parameters

traceId
string The unique identifier of the trace
feedback
Feedback object containing score and optional comment
comment?
string Optional textual feedback
score
number Numerical score for the trace

Returns

void void

Example

logger.traceFeedback('trace-123', {
  score: 4,
  comment: 'Good results but could be faster'
});

traceGeneration()

traceGeneration(traceId, config): Generation
Defined in: src/lib/logger/logger.ts:262 Creates a new generation (LLM call) associated with a trace.

Parameters

traceId
string The unique identifier of the trace
config
GenerationConfig Configuration for the generation

Returns

Generation A new generation instance associated with the trace

Example

const generation = logger.traceGeneration('trace-123', {
  id: 'gen-001',
  provider: 'openai',
  model: 'gpt-4',
  messages: [{ role: 'user', content: 'Hello!' }],
  modelParameters: { temperature: 0.7 }
});

traceInput()

traceInput(traceId, input): void
Defined in: src/lib/logger/logger.ts:340 Sets the input for a trace.

Parameters

traceId
string The unique identifier of the trace
input
string The input that triggered this trace

Returns

void void

Example

logger.traceInput('trace-123', 'Analyze customer sentiment from reviews');

traceMetadata()

traceMetadata(traceId, metadata): void
Defined in: src/lib/logger/logger.ts:461 Adds metadata to a trace for additional context and debugging.

Parameters

traceId
string The unique identifier of the trace
metadata
Record<string, unknown> Key-value pairs of metadata

Returns

void void

Example

logger.traceMetadata('trace-123', {
  requestId: 'req-456',
  userAgent: 'Mozilla/5.0...',
  processingTime: 1500
});

traceOutput()

traceOutput(traceId, output): void
Defined in: src/lib/logger/logger.ts:309 Sets the output for a trace.

Parameters

traceId
string The unique identifier of the trace
output
string The final output or result of the trace execution

Returns

void void

Example

logger.traceOutput('trace-123', 'The analysis is complete: 95% confidence');

traceRetrieval()

traceRetrieval(traceId, config): Retrieval
Defined in: src/lib/logger/logger.ts:296 Creates a new retrieval associated with a trace.

Parameters

traceId
string The unique identifier of the trace
config
RetrievalConfig Configuration for the retrieval

Returns

Retrieval A new retrieval instance associated with the trace

Example

const retrieval = logger.traceRetrieval('trace-123', {
  id: 'retrieval-001',
  name: 'Knowledge Base Search'
});

traceSpan()

traceSpan(traceId, config): Span
Defined in: src/lib/logger/logger.ts:356 Creates a new span associated with a trace.

Parameters

traceId
string The unique identifier of the trace
config
SpanConfig Configuration for the span

Returns

Span A new span instance associated with the trace

Example

const span = logger.traceSpan('trace-123', {
  id: 'span-001',
  name: 'Data Processing Phase'
});

traceTag()

traceTag(traceId, key, value): void
Defined in: src/lib/logger/logger.ts:384 Adds a tag to a trace for categorization and filtering.

Parameters

traceId
string The unique identifier of the trace
key
string The tag key
value
string The tag value

Returns

void void

Example

logger.traceTag('trace-123', 'operation', 'analysis');
logger.traceTag('trace-123', 'priority', 'high');

traceToolCall()

traceToolCall(traceId, config): ToolCall
Defined in: src/lib/logger/logger.ts:280 Creates a new tool call associated with a trace.

Parameters

traceId
string The unique identifier of the trace
config
ToolCallConfig Configuration for the tool call

Returns

ToolCall A new tool call instance associated with the trace

Example

const toolCall = logger.traceToolCall('trace-123', {
  id: 'tool-001',
  name: 'search_database',
  description: 'Search the product database',
  args: JSON.stringify({ query: 'laptop' })
});