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

@olostecnologia/olos-logger

v0.0.5

Published

Package to work with logs in Nodejs applications using Winston

Readme

@olostecnologia/olos-logger

Um pacote npm robusto para logging em aplicações Node.js usando Winston, otimizado para ambientes corporativos e seguindo as melhores práticas de logging.

📦 Instalação

npm install @olostecnologia/olos-logger

🚀 Uso Básico

Import/Require

// CommonJS
const OlosLogger = require('@olostecnologia/olos-logger');

// ES Modules
import OlosLogger from '@olostecnologia/olos-logger';

// Com funções de configuração
import OlosLogger, {
  setLogLevel,
  getCurrentLogLevel,
} from '@olostecnologia/olos-logger';

Logs Simples

OlosLogger.error('Mensagem de erro');
OlosLogger.warn('Mensagem de aviso');
OlosLogger.info('Mensagem informativa');
OlosLogger.debug('Mensagem de debug');

Logs com Objetos JSON

// Objetos são automaticamente formatados
OlosLogger.error('Erro na operação', {
  userId: 123,
  operation: 'database-query',
  error: {
    code: 'CONNECTION_TIMEOUT',
    message: 'Timeout na conexão',
  },
});

// Mensagem como objeto
OlosLogger.warn({
  message: 'Operação demorada',
  duration: 5000,
  threshold: 3000,
});

Stack Traces Automáticos

const error = new Error('Algo deu errado');
OlosLogger.error(error); // Stack trace será exibido automaticamente

📋 Formato JSON Estruturado

A partir da v0.0.5, todos os logs são gerados em formato JSON estruturado, proporcionando:

✅ Benefícios:

  • Parsing Automático: Logs podem ser facilmente processados por ferramentas
  • Estrutura Consistente: Mesmo formato independente do conteúdo
  • Metadata Separada: Propriedade metadata para dados adicionais
  • Compatibilidade: Funciona com ELK Stack, Fluentd, Splunk, etc.
  • Filtros Eficientes: Busca e filtros mais rápidos em sistemas centralizados

📊 Estrutura do Log:

{
  level: string;           // Nível do log (error, warn, info, etc.)
  message: string | object; // Mensagem principal
  timestamp: string;       // ISO timestamp
  service: string;         // Nome do serviço
  stack?: string;          // Stack trace (quando presente)
  metadata?: object;       // Dados adicionais estruturados
}

⚙️ Configuração de Log Level

Configuração por Variáveis de Ambiente

O pacote verifica automaticamente as seguintes variáveis (em ordem de prioridade):

  1. LOG_LEVEL - Padrão recomendado
  2. DEBUG_LEVEL - Compatibilidade
  3. NODE_ENV - Automático (development = debug, outros = info)
# Definir nível de log
export LOG_LEVEL=debug
export NODE_ENV=development

Configuração Dinâmica

import { setLogLevel, getCurrentLogLevel } from '@olostecnologia/olos-logger';

// Verificar nível atual
console.log('Nível atual:', getCurrentLogLevel()); // 'info'

// Alterar nível dinamicamente
setLogLevel('debug');
setLogLevel('error');

// Nível inválido gerará warning
setLogLevel('invalid'); // ⚠️ Warning + não altera

📊 Níveis de Log Disponíveis

| Nível | Valor | Descrição | | --------- | ----- | --------------------------- | | error | 0 | Apenas erros críticos | | warn | 1 | Erros + avisos | | info | 2 | Informações gerais (padrão) | | http | 3 | Logs HTTP/requests | | verbose | 4 | Logs detalhados | | debug | 5 | Logs de debugging | | silly | 6 | Todos os logs possíveis |

🎨 Formato de Saída

Log Simples (JSON)

{
  "level": "info",
  "message": "Operação completada",
  "timestamp": "2025-07-22T13:30:45.123Z",
  "service": "@olostecnologia/olos-logger"
}

Log com Metadata (JSON)

{
  "level": "error",
  "message": "Erro na operação",
  "timestamp": "2025-07-22T13:30:45.124Z",
  "service": "@olostecnologia/olos-logger",
  "metadata": {
    "userId": 123,
    "operation": "database-query",
    "requestId": "req-456",
    "duration": 150
  }
}

Log com Stack Trace (JSON)

{
  "level": "error",
  "message": "Algo deu errado",
  "timestamp": "2025-07-22T13:30:45.125Z",
  "service": "@olostecnologia/olos-logger",
  "stack": "Error: Algo deu errado\n    at Object.<anonymous> (/app/index.js:5:15)\n    at Module._compile (internal/modules/cjs/loader.js:1063:30)",
  "metadata": {
    "host": "db.example.com",
    "port": 5432,
    "retries": 3
  }
}

🔧 Configuração Avançada

Adicionando Transports Customizados

import { addTransport, removeTransport } from '@olostecnologia/olos-logger';
import winston from 'winston';

// Adicionar transport de arquivo
const fileTransport = new winston.transports.File({
  filename: 'app.log',
  level: 'error',
});

addTransport(fileTransport);

// Remover transport
removeTransport(fileTransport);

🌍 Variáveis de Ambiente Suportadas

| Variável | Descrição | Padrão | | ------------------ | ---------------------------------- | ----------------- | | LOG_LEVEL | Nível de log principal | info | | DEBUG_LEVEL | Nível de log (compatibilidade) | info | | NODE_ENV | Ambiente (development = debug) | info | | npm_package_name | Nome do serviço (automático) | unknown-service |

📋 Melhores Práticas

1. Use níveis apropriados

OlosLogger.error('Falha crítica no sistema'); // Apenas falhas críticas
OlosLogger.warn('Cache miss, using fallback'); // Situações não ideais
OlosLogger.info('User login successful'); // Fluxo normal importante
OlosLogger.debug('Processing item 1 of 100'); // Debugging detalhado

2. Estruture metadados

OlosLogger.info('API request completed', {
  method: 'POST',
  endpoint: '/api/users',
  statusCode: 201,
  duration: 145,
  userId: 123,
});

3. Use objetos para contexto

// ✅ Bom
OlosLogger.error('Database connection failed', {
  host: 'db.example.com',
  port: 5432,
  database: 'app_prod',
  error: err.message,
});

// ❌ Evite
OlosLogger.error(`Database connection failed: ${err.message}`);

🔄 Migração de Versões Antigas

Se você estava usando a versão anterior:

// Antes
const logger = require('@olostecnologia/olos-logger');

// Agora (compatível)
const OlosLogger = require('@olostecnologia/olos-logger');

// Novo (recomendado)
const {
  default: OlosLogger,
  setLogLevel,
} = require('@olostecnologia/olos-logger');

📝 Changelog

v0.0.5

  • BREAKING CHANGE: Formato de saída alterado para JSON estruturado
  • ✅ Propriedade metadata preservada e separada
  • ✅ Stack traces em formato JSON
  • ✅ Melhor compatibilidade com sistemas de log centralizados
  • ✅ Parsing mais eficiente dos logs

v0.0.3

  • ✅ Configuração dinâmica de log level
  • ✅ Suporte aprimorado para objetos JSON
  • ✅ Stack traces automáticos
  • ✅ Múltiplas variáveis de ambiente
  • ✅ Metadados estruturados
  • ✅ Funções de gerenciamento de transports

📄 Licença

ISC - Veja o arquivo LICENSE para detalhes.

👥 Contribuição

Desenvolvido por OLos Tecnologia
Email: [email protected]

Para contribuições, abra uma issue ou pull request no GitHub.