xiaohongshu
xiaohongshu
fullstory-logging
Comprehensive guide for implementing Fullstory's Logging API (log method) for web applications. Teaches proper log level usage, message formatting, and capturing application logs in session replay. Includes detailed good/bad examples for error tracking, debugging, and operational monitoring to he...
Full skill instructions
Fullstory's Logging API allows developers to send log messages directly to Fullstory sessions without logging to the browser's developer console. These logs appear in the session replay, providing valuable context for debugging user issues, tracking application state, and understanding user workflows.
Key use cases:
| Level | Use For | Console Equivalent |
|---|---|---|
'log' | General information | console.log() |
'info' | Informational messages | console.info() |
'warn' | Warning conditions | console.warn() |
'error' | Error conditions | console.error() |
'debug' | Debug information | console.debug() |
| Behavior | Description |
|---|---|
| Not in browser console | Logs only appear in Fullstory, not browser console |
| Session context | Logs viewable in session replay timeline |
| Timestamp | Automatically timestamped by Fullstory |
| Searchable | Can search sessions by log content |
| Use FS Logging | Use Console |
|---|---|
| Production errors you want in replay | Development-only debugging |
| State changes for support context | Verbose tracing during development |
| User action audit trails | Performance timing logs |
| Integration errors | Internal debugging |
FS('log', {
level: string, // Optional: Log level (default: 'log')
msg: string, // Required: Message to log
})
await FS('logAsync', {
level: string,
msg: string,
})
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
level | string | No | 'log' | Log level: 'log', 'info', 'warn', 'error', 'debug' |
msg | string | Yes | - | Message to log (string only) |
// GOOD: Log errors with context for session replay
function logError(error, context = {}) {
// Create detailed error message
const errorDetails = [
`Error: ${error.message}`,
`Type: ${error.name}`,
`Context: ${JSON.stringify(context)}`,
error.stack ? `Stack:\n${error.stack}` : '',
]
.filter(Boolean)
.join('\n')
// Send to Fullstory
FS('log', {
level: 'error',
msg: errorDetails,
})
// Also send to your error tracking service
// Sentry, Bugsnag, etc.
}
// Usage
try {
await processPayment(paymentData)
} catch (error) {
logError(error, {
action: 'processPayment',
paymentMethod: paymentData.method,
amount: paymentData.amount,
})
showErrorToUser('Payment failed. Please try again.')
}
Why this is good:
// GOOD: Log API responses for debugging
async function fetchWithLogging(url, options = {}) {
const startTime = Date.now()
FS('log', {
level: 'info',
msg: `API Request: ${options.method || 'GET'} ${url}`,
})
try {
const response = await fetch(url, options)
const duration = Date.now() - startTime
if (!response.ok) {
FS('log', {
level: 'warn',
msg: `API Error: ${response.status} ${response.statusText} - ${url} (${duration}ms)`,
})
} else {
FS('log', {
level: 'log',
msg: `API Success: ${response.status} - ${url} (${duration}ms)`,
})
}
return response
} catch (error) {
const duration = Date.now() - startTime
FS('log', {
level: 'error',
msg: `API Failed: ${error.message} - ${url} (${duration}ms)`,
})
throw error
}
}
// Usage
const response = await fetchWithLogging('/api/users/123')
Why this is good:
// GOOD: Create audit trail of important user actions
class AuditLogger {
static log(action, details = {}) {
const message = [
`Action: ${action}`,
`Time: ${new Date().toISOString()}`,
`Details: ${JSON.stringify(details)}`,
].join(' | ')
FS('log', {
level: 'info',
msg: message,
})
}
static logNavigation(from, to) {
this.log('Navigation', {from, to})
}
static logFormSubmit(formName, success) {
this.log('Form Submit', {
formName,
success,
timestamp: Date.now(),
})
}
static logFeatureUsed(featureName, context = {}) {
this.log('Feature Used', {featureName, ...context})
}
static logSettingChanged(setting, oldValue, newValue) {
this.log('Setting Changed', {
setting,
oldValue: String(oldValue),
newValue: String(newValue),
})
}
}
// Usage
AuditLogger.logNavigation('/dashboard', '/settings')
AuditLogger.logFormSubmit('contact-form', true)
AuditLogger.logFeatureUsed('export', {format: 'csv', rows: 500})
AuditLogger.logSettingChanged('notifications', true, false)
Why this is good:
// GOOD: Log important state changes for debugging
function createLoggingStore(initialState, storeName) {
let state = initialState
return {
getState() {
return state
},
setState(updates, actionName = 'unknown') {
const prevState = {...state}
state = {...state, ...updates}
// Log the state change
FS('log', {
level: 'log',
msg: `[${storeName}] ${actionName}: ${JSON.stringify({
changes: Object.keys(updates),
newValues: updates,
})}`,
})
return state
},
}
}
// Usage
const cartStore = createLoggingStore({items: [], total: 0}, 'CartStore')
cartStore.setState(
{
items: [...cartStore.getState().items, newItem],
total: cartStore.getState().total + newItem.price,
},
'addItem',
)
// Logs: [CartStore] addItem: {"changes":["items","total"],"newValues":{...}}
Why this is good:
// GOOD: Log third-party integration errors
class IntegrationLogger {
constructor(integrationName) {
this.integrationName = integrationName
}
logConnectionAttempt() {
FS('log', {
level: 'info',
msg: `[${this.integrationName}] Attempting connection...`,
})
}
logConnected() {
FS('log', {
level: 'info',
msg: `[${this.integrationName}] Connected successfully`,
})
}
logDisconnected(reason) {
FS('log', {
level: 'warn',
msg: `[${this.integrationName}] Disconnected: ${reason}`,
})
}
logError(operation, error) {
FS('log', {
level: 'error',
msg: `[${this.integrationName}] ${operation} failed: ${error.message}`,
})
}
logTimeout(operation, timeoutMs) {
FS('log', {
level: 'warn',
msg: `[${this.integrationName}] ${operation} timed out after ${timeoutMs}ms`,
})
}
}
// Usage
const stripeLogger = new IntegrationLogger('Stripe')
async function initializeStripe() {
stripeLogger.logConnectionAttempt()
try {
await stripe.init()
stripeLogger.logConnected()
} catch (error) {
stripeLogger.logError('initialization', error)
throw error
}
}
Why this is good:
// GOOD: Conditional verbose logging for debugging
class DebugLogger {
static isDebugMode() {
return (
localStorage.getItem('fs_debug') === 'true' ||
new URLSearchParams(window.location.search).has('debug')
)
}
static debug(message, data = null) {
if (this.isDebugMode()) {
const fullMessage = data
? `[DEBUG] ${message}\nData: ${JSON.stringify(data, null, 2)}`
: `[DEBUG] ${message}`
FS('log', {
level: 'debug',
msg: fullMessage,
})
// Also log to console in debug mode
console.debug(message, data)
}
}
static trace(functionName, args) {
if (this.isDebugMode()) {
FS('log', {
level: 'debug',
msg: `[TRACE] ${functionName}(${args.map((a) => JSON.stringify(a)).join(', ')})`,
})
}
}
static measure(label, fn) {
if (!this.isDebugMode()) {
return fn()
}
const start = performance.now()
const result = fn()
const duration = performance.now() - start
FS('log', {
level: 'debug',
msg: `[PERF] ${label}: ${duration.toFixed(2)}ms`,
})
return result
}
}
// Usage
DebugLogger.debug('Processing checkout', {cartId, itemCount})
DebugLogger.trace('calculateTotal', [items, taxRate, discount])
const total = DebugLogger.measure('calculateTotal', () => calculateTotal(items))
Why this is good:
// BAD: Logging sensitive/PII data
FS('log', {
level: 'info',
msg: `User login: email=${user.email}, password=${user.password}`, // BAD: Password!
})
FS('log', {
level: 'info',
msg: `Payment: card=${user.creditCard}`, // BAD: Credit card!
})
Why this is bad:
CORRECTED VERSION:
// GOOD: Sanitize sensitive data
FS('log', {
level: 'info',
msg: `User login: userId=${user.id}, method=password`,
})
FS('log', {
level: 'info',
msg: `Payment: cardLast4=${user.creditCard.slice(-4)}, type=${user.cardType}`,
})
// BAD: Logging too much
document.addEventListener('mousemove', (e) => {
FS('log', {
level: 'debug',
msg: `Mouse: ${e.clientX}, ${e.clientY}`,
}) // BAD: Fires hundreds of times per second!
})
for (let i = 0; i < 10000; i++) {
FS('log', {
level: 'log',
msg: `Processing item ${i}`,
}) // BAD: 10,000 log calls!
}
Why this is bad:
CORRECTED VERSION:
// GOOD: Log significant events only
FS('log', {
level: 'info',
msg: `Processing started: 10000 items`,
})
// ... process items ...
FS('log', {
level: 'info',
msg: `Processing complete: 10000 items in ${duration}ms`,
})
// BAD: Passing objects instead of strings
FS('log', {
level: 'error',
msg: {error: 'Something failed', code: 500}, // BAD: Object!
})
FS('log', {
level: 'log',
msg: ['item1', 'item2', 'item3'], // BAD: Array!
})
Why this is bad:
CORRECTED VERSION:
// GOOD: Stringify objects
FS('log', {
level: 'error',
msg: JSON.stringify({error: 'Something failed', code: 500}),
})
FS('log', {
level: 'log',
msg: `Items: ${['item1', 'item2', 'item3'].join(', ')}`,
})
// BAD: Vague error logging
try {
await doSomething()
} catch (error) {
FS('log', {
level: 'error',
msg: 'An error occurred', // BAD: No useful information!
})
}
Why this is bad:
CORRECTED VERSION:
// GOOD: Detailed error logging
try {
await doSomething()
} catch (error) {
FS('log', {
level: 'error',
msg: `doSomething failed: ${error.message}\nStack: ${error.stack}`,
})
}
// BAD: Misusing log levels
FS('log', {
level: 'error',
msg: 'User clicked button', // BAD: Not an error!
})
FS('log', {
level: 'debug',
msg: 'Database connection failed!', // BAD: This is an error!
})
Why this is bad:
CORRECTED VERSION:
// GOOD: Appropriate log levels
FS('log', {
level: 'info',
msg: 'User clicked button: submit-form',
})
FS('log', {
level: 'error',
msg: 'Database connection failed: timeout after 30s',
})
// BAD: Using logs for analytics instead of events
FS('log', {
level: 'info',
msg: 'Purchase completed: $99.99, order_id: ORD-123',
})
// Missing: FS('trackEvent', ...) for proper analytics!
Why this is bad:
CORRECTED VERSION:
// GOOD: Use events for analytics, logs for debugging
FS('trackEvent', {
name: 'Order Completed',
properties: {
orderId: 'ORD-123',
revenue: 99.99,
},
})
// Log additional debugging context if needed
FS('log', {
level: 'info',
msg: 'Order ORD-123 processed successfully',
})
// Centralized logging utility
const AppLogger = {
_formatMessage(prefix, message, data) {
let formatted = `[${prefix}] ${message}`
if (data) {
formatted += `\nData: ${JSON.stringify(data)}`
}
return formatted
},
log(message, data) {
if (typeof FS !== 'undefined') {
FS('log', {level: 'log', msg: this._formatMessage('LOG', message, data)})
}
},
info(message, data) {
if (typeof FS !== 'undefined') {
FS('log', {level: 'info', msg: this._formatMessage('INFO', message, data)})
}
},
warn(message, data) {
if (typeof FS !== 'undefined') {
FS('log', {level: 'warn', msg: this._formatMessage('WARN', message, data)})
}
},
error(message, error, data) {
if (typeof FS !== 'undefined') {
let errorMsg = this._formatMessage('ERROR', message, data)
if (error) {
errorMsg += `\nError: ${error.message}\nStack: ${error.stack}`
}
FS('log', {level: 'error', msg: errorMsg})
}
},
debug(message, data) {
if (typeof FS !== 'undefined' && this._isDebugEnabled()) {
FS('log', {level: 'debug', msg: this._formatMessage('DEBUG', message, data)})
}
},
_isDebugEnabled() {
return localStorage.getItem('fs_debug') === 'true'
},
}
// Usage
AppLogger.info('Page loaded', {path: window.location.pathname})
AppLogger.warn('Slow API response', {endpoint: '/api/data', duration: 5000})
AppLogger.error('Checkout failed', error, {cartId: '123'})
// Create loggers scoped to modules/components
function createScopedLogger(scope) {
return {
log(message, data) {
FS('log', {
level: 'log',
msg: `[${scope}] ${message}${data ? ` | ${JSON.stringify(data)}` : ''}`,
})
},
info(message, data) {
FS('log', {
level: 'info',
msg: `[${scope}] ${message}${data ? ` | ${JSON.stringify(data)}` : ''}`,
})
},
warn(message, data) {
FS('log', {
level: 'warn',
msg: `[${scope}] ${message}${data ? ` | ${JSON.stringify(data)}` : ''}`,
})
},
error(message, error) {
FS('log', {
level: 'error',
msg: `[${scope}] ${message}${error ? ` | ${error.message}` : ''}`,
})
},
}
}
// Usage in different modules
const authLogger = createScopedLogger('Auth')
authLogger.info('Login attempt', {method: 'password'})
const paymentLogger = createScopedLogger('Payment')
paymentLogger.error('Payment failed', new Error('Insufficient funds'))
// Fetch wrapper with automatic logging
function createLoggingFetch() {
const originalFetch = window.fetch
return async function loggingFetch(url, options = {}) {
const requestId = Math.random().toString(36).substr(2, 9)
const method = options.method || 'GET'
const startTime = Date.now()
FS('log', {
level: 'info',
msg: `[HTTP:${requestId}] → ${method} ${url}`,
})
try {
const response = await originalFetch(url, options)
const duration = Date.now() - startTime
const level = response.ok ? 'info' : 'warn'
FS('log', {
level,
msg: `[HTTP:${requestId}] ← ${response.status} ${method} ${url} (${duration}ms)`,
})
return response
} catch (error) {
const duration = Date.now() - startTime
FS('log', {
level: 'error',
msg: `[HTTP:${requestId}] ✕ ${method} ${url} - ${error.message} (${duration}ms)`,
})
throw error
}
}
}
// Apply globally
window.fetch = createLoggingFetch()
Symptom: FS('log') called but logs not in session replay
Common Causes:
Solutions:
Symptom: Long messages appear cut off
Common Causes:
Solutions:
When helping developers with Logging API:
Always emphasize:
Common mistakes to watch for:
Questions to ask developers:
Best practices to recommend:
This skill document was created to help Agent understand and guide developers in implementing Fullstory's Logging API correctly for web applications.
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience