@giolc/logger
v0.1.3
Published
<img width="605" height="177" alt="image" src="https://github.com/user-attachments/assets/d33cef0d-51e2-491b-aa17-5d5d848cdea8" /> <img width="604" height="185" alt="image" src="https://github.com/user-attachments/assets/33be268f-ecdc-492a-8fca-06998b111
Readme
@giolc/logger
English
Overview
@giolc/logger is a logging toolkit written in TypeScript that honors the RFC 5424 severity levels and prioritizes composability. It offers contextual logging, interchangeable transports/formatters, synchronous and reactive dispatch strategies, plus optional metrics.
Features
- RFC 5424 levels (
EmergencythroughDebug) with typed helpers. - Contextual API (
Logger.for(ctx)) and anAppLoggersingleton for fast initialization. - Available dispatchers:
SyncDispatcher(deterministic emission) andReactiveDispatcher(async batching with auto-shutdown on inactivity). - Included transports: console with level routing, memory with a bounded buffer, filesystem append, and HTTP POST; all configurable via
TransportResolver. DefaultFormatterwith emoji/ASCII headers, ANSI colors, and localized timestamps.- Metrics (
built,dispatched,filtered,transportErrors) with a live callback. - Utilities to normalize messages, build and throw errors, and style text.
AppLogger.reset()to clear singleton state between tests or runtime reconfiguration.
Repository Structure
packages/logger: source code, tests, and package build.- Root scripts:
build,pack,start,test,clean,update.
Installation & Scripts
npm install
npm run build # Builds @giolc/logger with tsup
npm run pack # Builds + packs the library
npm run test # Runs Vitest under packages/loggerUsage Example
import { Logger, Level } from '@giolc/logger'
import { MemoryTransport } from '@giolc/logger/Transport'
const memory = new MemoryTransport({ maxBufferSize: 200 })
const logger = new Logger({
minLevel: Level.Debug,
transports: [memory, 'console'],
dispatcher: 'reactive',
metrics: { enabled: true, onUpdate: console.log },
})
const authLogger = logger.for('AuthService')
authLogger.info('Started')
authLogger.critical(Error, 'Boom') // throws the errorAppLogger Singleton
import { AppLogger } from '@giolc/logger'
AppLogger.init({ transports: ['console'], metrics: { enabled: true } })
AppLogger.warn('Warming up cache')
console.log(AppLogger.metrics)
// Useful for tests to avoid singleton leakage
afterEach(() => {
AppLogger.reset()
})Dispatchers & Transports
| Dispatcher | When to use it | Highlights |
|------------|----------------|------------|
| sync | CLIs or services that need strict ordering | Immediate emission, no buffering |
| reactive | Web apps or high-throughput services | MessageChannel/timer scheduling, batching, auto-dispose on inactivity, drain() |
Transports:
ConsoleTransport: uses the console channel by level and honors formatter settings.MemoryTransport: stores formatted strings, supports limits, and exposeslogs,snapshot(), andclear().
Extending transports means inheriting from LogTransport and defining performEmit.
Formatting
DefaultFormatter options:
withEmojis: switch between emoji and ASCII.color: enable ANSI colors.localeDate: set the timestamp locale.
You can inject custom formatters via TransportParams.
Metrics & Observability
Enable with metrics: { enabled: true, onUpdate?: (snapshot) => void }. Counters:
built: logs constructed.dispatched: emitted after passing the filter.filtered: discarded because ofminLevel.transportErrors: failures while emitting through transports.
onUpdate fires every time one of those counters increases (typically twice per log: once for built, once for the final outcome), so plan your observers with that cadence in mind.
Testing & Quality
npm run testruns Vitest (packages/logger/tests/*).ReactiveDispatcherexposesdrain()to ensure deterministic results.- Add new tests under
packages/logger/tests.
Build & Publication
npm run build: creates CJS/ESM/d.ts bundles indistwith tsup.npm run pack: generatesgiolc-logger-x.x.x.tgz.
Español
Descripcion General
@giolc/logger es un toolkit de logging escrito en TypeScript que respeta los niveles de severidad del RFC 5424 y prioriza la componibilidad. Ofrece logging contextual, transportes/formatters intercambiables, estrategias de dispatch sincronicas y reactivas, ademas de metricas opcionales.
Caracteristicas
- Niveles RFC 5424 (
EmergencyaDebug) con helpers tipados. - API contextual (
Logger.for(ctx)) y un singletonAppLoggerpara inicializaciones rapidas. - Dispatchers disponibles:
SyncDispatcher(emision deterministica) yReactiveDispatcher(batch asincrono con auto-apagado por inactividad). - Transportes incluidos: consola con ruteo por nivel, memoria con buffer limitado, archivos con append y HTTP POST; todos configurables via
TransportResolver. DefaultFormattercon headers emoji/ASCII, colores ANSI y timestamps localizados.- Metricas (
built,dispatched,filtered,transportErrors) con callback en vivo. - Utilidades para normalizar mensajes, construir y lanzar errores y estilizar texto.
AppLogger.reset()para limpiar el estado singleton entre pruebas o reconfiguraciones.
Estructura del Repositorio
packages/logger: codigo fuente, pruebas y build del paquete.- Scripts raiz:
build,pack,start,test,clean,update.
Instalacion y Scripts
npm install
npm run build # Compila @giolc/logger con tsup
npm run pack # Compila + empaqueta
npm run test # Ejecuta Vitest en packages/loggerEjemplo de Uso
import { Logger, Level } from '@giolc/logger'
import { MemoryTransport } from '@giolc/logger/Transport'
const memoria = new MemoryTransport({ maxBufferSize: 200 })
const logger = new Logger({
minLevel: Level.Debug,
transports: [memoria, 'console'],
dispatcher: 'reactive',
metrics: { enabled: true, onUpdate: console.log },
})
const authLogger = logger.for('AuthService')
authLogger.info('Iniciado')
authLogger.critical(Error, 'Boom') // lanza el errorSingleton AppLogger
import { AppLogger } from '@giolc/logger'
AppLogger.init({ transports: ['console'], metrics: { enabled: true } })
AppLogger.warn('Calentando caché')
console.log(AppLogger.metrics)
// En pruebas
afterEach(() => {
AppLogger.reset()
})Dispatchers y Transportes
| Dispatcher | Cuando usarlo | Destacados |
|------------|----------------|------------|
| sync | CLIs o servicios que necesitan orden estricto | Emision inmediata, sin buffering |
| reactive | Apps web o servicios de alto throughput | Programacion con MessageChannel/timers, batching, auto-dispose por inactividad, drain() |
Transportes:
ConsoleTransport: usa el canal de consola segun el nivel y respeta la configuracion del formatter.MemoryTransport: almacena strings formateadas, admite limite y exponelogs,snapshot()yclear().
Extender transportes implica heredar de LogTransport y definir performEmit.
Formateo
Opciones de DefaultFormatter:
withEmojis: alterna entre emoji y ASCII.color: habilita colores ANSI.localeDate: define la localizacion del timestamp.
Puedes inyectar formatters propios mediante TransportParams.
Metricas y Observabilidad
Activa con metrics: { enabled: true, onUpdate?: (snapshot) => void }. Contadores:
built: logs construidos.dispatched: emitidos tras pasar el filtro.filtered: descartados porminLevel.transportErrors: fallos al emitir en transportes.
onUpdate se ejecuta cada vez que incrementa un contador (normalmente dos veces por log: built + resultado), así que toma en cuenta ese ritmo para tus consumidores.
Pruebas y Calidad
npm run testcorre Vitest (packages/logger/tests/*).ReactiveDispatcherexponedrain()para asegurar resultados deterministas.- Agrega nuevas pruebas bajo
packages/logger/tests.
Build y Publicación
npm run build: crea bundles CJS/ESM/d.ts endistcon tsup.npm run pack: generagiolc-logger-x.x.x.tgz.
