npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

soad-logs

v1.0.9

Published

SDK para enviar logs de procesos con React Native y Web

Readme

Logs SDK

Un SDK de logging robusto y fácil de usar para aplicaciones web y React Native que permite rastrear eventos, errores y comportamiento del usuario con información detallada del dispositivo.

🚀 Características

  • Singleton Pattern: Una sola instancia del SDK en toda la aplicación
  • Detección automática de dispositivo: Recopila información del navegador/dispositivo automáticamente
  • Eventos predefinidos: Más de 25 eventos comunes listos para usar
  • Gestión de procesos: Agrupa logs por sesiones/procesos
  • Soporte multiplataforma: Compatible con web y React Native
  • TypeScript: Completamente tipado para mejor experiencia de desarrollo

📦 Instalación

npm install soad-logs
# o
yarn add soad-logs

🔧 Configuración inicial

import { logsSDK, DefaultEvents, ProcessType } from 'soad-logs';

// Configurar el cliente ID (requerido)
logsSDK.setClientId('tu-client-id-unico');

// Opcional: Configurar información del dispositivo manualmente
logsSDK.setDeviceInfo({
userAgent: 'Custom User Agent',
platform: 'iOS',
// ... más información
});

📖 Uso básico

1. Iniciar un proceso

// Iniciar un nuevo proceso de logging
const processId = await logsSDK.startProcess();
console.log('Proceso iniciado:', processId);

2. Enviar logs

// Log básico
await logsSDK.log({
eventName: 'User Action',
description: 'Usuario hizo clic en el botón principal',
processType: ProcessType.info,
userInfo: 'user123',
extras: JSON.stringify({ buttonId: 'main-cta' })
});

// Usando eventos predefinidos
await logsSDK.log({
...DefaultEvents.ButtonClicked('login-button'),
processType: ProcessType.info,
userInfo: 'user123'
});

3. Gestión de procesos

// Obtener el proceso actual
const currentProcess = logsSDK.getCurrentProcessId();

// Resetear el proceso (para iniciar uno nuevo)
logsSDK.resetProcess();

// Usar un proceso específico
await logsSDK.log({
eventName: 'Custom Event',
description: 'Evento con proceso específico',
processType: ProcessType.success,
processId: 'proceso-especifico-123'
});

🎯 Eventos predefinidos

El SDK incluye eventos predefinidos para casos de uso comunes:

Ciclo de vida de la app

DefaultEvents.AppOpen
DefaultEvents.AppClosed
DefaultEvents.AppBackground
DefaultEvents.AppForeground

Navegación

DefaultEvents.ScreenEntered('home')
DefaultEvents.ScreenExited('profile')

Acciones del usuario

DefaultEvents.ButtonClicked('submit-btn')
DefaultEvents.LinkClicked('https://example.com')
DefaultEvents.FormSubmitted('contact-form')
DefaultEvents.ItemSelected('product-123')
DefaultEvents.ToggleChanged('notifications', true)

Autenticación

DefaultEvents.UserLoggedIn('email')
DefaultEvents.UserLoggedOut
DefaultEvents.UserSignedUp('google')
DefaultEvents.PasswordChanged

Errores y mensajes

DefaultEvents.ErrorOccurred('Network timeout')
DefaultEvents.WarningOccurred('Low battery')
DefaultEvents.InfoMessage('Data synced successfully')

Notificaciones

DefaultEvents.PushNotificationReceived('New message')
DefaultEvents.PushNotificationOpened('Promotion alert')

Compras

DefaultEvents.PurchaseInitiated('premium-plan')
DefaultEvents.PurchaseCompleted('premium-plan')
DefaultEvents.PurchaseFailed('premium-plan')

Permisos del dispositivo

DefaultEvents.LocationAccessGranted
DefaultEvents.CameraAccessGranted
DefaultEvents.MicrophoneAccessGranted
DefaultEvents.DeviceOrientationChanged('landscape')

🔍 Ejemplo completo

import { logsSDK, DefaultEvents, ProcessType } from 'soad-logs';

class AppLogger {
async initialize() {
// Configurar el SDK
logsSDK.setClientId('mi-app-v1.0');

    // Iniciar proceso
    await logsSDK.startProcess();
    
    // Log de apertura de app
    await logsSDK.log({
      ...DefaultEvents.AppOpen,
      processType: ProcessType.info,
      userInfo: 'anonymous-user'
    });
}

async logUserAction(action: string, details?: any) {
await logsSDK.log({
...DefaultEvents.ButtonClicked(action),
processType: ProcessType.info,
extras: details ? JSON.stringify(details) : undefined
});
}

async logError(error: Error) {
await logsSDK.log({
...DefaultEvents.ErrorOccurred(error.message),
processType: ProcessType.error,
extras: JSON.stringify({
stack: error.stack,
timestamp: new Date().toISOString()
})
});
}
}

// Uso
const logger = new AppLogger();
await logger.initialize();
await logger.logUserAction('purchase', { productId: 'pro-plan' });

📱 Información del dispositivo

El SDK recopila automáticamente la siguiente información del dispositivo:

  • userAgent: Información del navegador/app
  • language: Idioma del dispositivo
  • platform: Plataforma (iOS, Android, Web)
  • screenResolution: Resolución de pantalla
  • pixelRatio: Ratio de píxeles
  • windowSize: Tamaño de ventana
  • connection: Tipo de conexión de red
  • connectionDownLink: Velocidad de descarga

🔧 API Reference

LogsSDK

Métodos principales

  • setClientId(clientId: string): Configura el ID del cliente
  • setDeviceInfo(deviceInfo: DeviceInfo): Configura información del dispositivo manualmente
  • startProcess(): Promise<string>: Inicia un nuevo proceso y retorna su ID
  • log(payload: LogPayload): Promise<any>: Envía un log
  • resetProcess(): Resetea el proceso actual
  • getCurrentProcessId(): string | null: Obtiene el ID del proceso actual

Tipos

ProcessType

enum ProcessType {
success = 'success',
error = 'error',
warning = 'warning',
info = 'info'
}

LogPayload

interface LogPayload {
eventName: string;
description: string;
userInfo?: string;
extras?: string;
processId?: string;
processType: ProcessType;
}

DeviceInfo

interface DeviceInfo {
userAgent?: string;
language?: string;
platform?: string;
screenResolution?: string;
pixelRatio?: string;
windowSize?: string;
connection?: string;
connectionDownLink?: string;
cameras?: string;
geolocation?: string;
}

🚨 Manejo de errores

try {
await logsSDK.startProcess();
} catch (error) {
console.error('Error al iniciar proceso:', error);
// El SDK lanzará errores si no se configura clientId
}

try {
await logsSDK.log({
eventName: 'Test Event',
description: 'Evento de prueba',
processType: ProcessType.info
});
} catch (error) {
console.error('Error al enviar log:', error);
// Error si no hay processId disponible
}

🌐 Soporte para React Native

El SDK es compatible con React Native. En entornos móviles, la detección automática de dispositivo retornará un objeto vacío, por lo que se recomienda usar setDeviceInfo() para proporcionar información específica del dispositivo móvil.

// En React Native
import { Platform } from 'react-native';

logsSDK.setDeviceInfo({
platform: Platform.OS,
// ... otra información específica del dispositivo móvil
});

📄 Licencia

MIT License - ver el archivo LICENSE para más detalles.

🤝 Contribuir

Las contribuciones son bienvenidas. Por favor, abre un issue o envía un pull request.