### Install and Link Winston-Loki for Local Development (Shell) Source: https://github.com/janianttonen/winston-loki/blob/development/README.md This command sequence outlines the steps to install and link the `winston-loki` package for local development. It involves installing dependencies, linking the package globally, and then linking it into your project's `node_modules` directory, allowing for immediate testing of changes. ```shell npm install npm link cd ~/your_project npm link winston-loki npm install ``` -------------------------------- ### Full Winston Loki Integration Example Source: https://context7.com/janianttonen/winston-loki/llms.txt Provides a complete Node.js application example integrating Winston Loki with multiple transports, including console logging for development. It showcases comprehensive configuration options like default metadata, batching, and graceful shutdown. ```javascript const winston = require('winston'); const LokiTransport = require('winston-loki'); // Create logger with multiple transports const logger = winston.createLogger({ level: 'debug', defaultMeta: { service: 'user-api', version: '2.1.0' }, transports: [ // Console transport for local development new winston.transports.Console({ format: winston.format.combine( winston.format.colorize(), winston.format.simple() ) }), // Loki transport for centralized logging new LokiTransport({ host: process.env.LOKI_HOST || 'http://127.0.0.1:3100', json: true, batching: true, interval: 5, labels: { job: 'user-api', environment: process.env.NODE_ENV || 'development' }, replaceTimestamp: true, gracefulShutdown: true, timeout: 10000, onConnectionError: (err) => { console.error('Loki error:', err.message); } }) ] }); // Example usage in an Express-like application function handleRequest(req) { const requestId = Math.random().toString(36).substr(2, 9); logger.info({ message: 'Request received', labels: { requestId, method: req.method, path: req.path } }); try { // Process request... logger.debug({ message: 'Processing completed', labels: { requestId, duration: '45ms' } }); } catch (error) { logger.error({ message: `Request failed: ${error.message}`, labels: { requestId, errorType: error.name } }); } } // Simulate requests handleRequest({ method: 'GET', path: '/api/users' }); handleRequest({ method: 'POST', path: '/api/users' }); ``` -------------------------------- ### Use Protobuf Transport Mode with Snappy Compression (JavaScript) Source: https://context7.com/janianttonen/winston-loki/llms.txt This example demonstrates using Protobuf encoding with snappy compression for more efficient data transfer to Loki. This mode is typically the default when snappy binaries are available. It's ideal for high-throughput scenarios where minimizing network overhead is crucial. ```javascript const winston = require('winston'); const LokiTransport = require('winston-loki'); const logger = winston.createLogger({ transports: [ new LokiTransport({ host: 'http://127.0.0.1:3100', json: false, // Use Protobuf with snappy compression labels: { job: 'high-throughput-service' }, interval: 1 // Send batches every second for high volume }) ] }); // High-volume logging with efficient Protobuf encoding for (let i = 0; i < 1000; i++) { logger.info(`Event ${i} processed`, { eventId: i }); } ``` -------------------------------- ### Configure Basic Authentication for Loki Transport Source: https://context7.com/janianttonen/winston-loki/llms.txt Shows how to configure basic authentication for the LokiTransport, suitable for local Loki instances or Grafana Cloud Loki using API tokens. It includes examples for both scenarios. ```javascript const winston = require('winston'); const LokiTransport = require('winston-loki'); // For local Loki with basic authentication const loggerLocal = winston.createLogger({ transports: [ new LokiTransport({ host: 'http://127.0.0.1:3100', json: true, basicAuth: 'username:password', labels: { job: 'winston-loki-example' } }) ] }); // For Grafana Cloud Loki const loggerCloud = winston.createLogger({ transports: [ new LokiTransport({ host: 'https://logs-prod-006.grafana.net', json: true, basicAuth: '372040:glc_eyJvIjoiMTIzNDU2...', // USER_ID:GRAFANA_CLOUD_TOKEN labels: { app: 'my-cloud-app' }, format: winston.format.json(), replaceTimestamp: true, onConnectionError: (err) => console.error(err) }) ] }); loggerCloud.info('Connected to Grafana Cloud Loki'); ``` -------------------------------- ### Custom Winston Formatting for Loki Logs (JavaScript) Source: https://context7.com/janianttonen/winston-loki/llms.txt This example demonstrates how to apply custom Winston formatters to modify log output before it's sent to Loki. When a custom format is provided, the fully formatted message becomes the log line in Loki. This allows for complete control over the log's appearance and content. ```javascript const { createLogger, format } = require('winston'); const LokiTransport = require('winston-loki'); const logger = createLogger({ transports: [ new LokiTransport({ host: 'http://localhost:3100', json: true, labels: { module: 'api', app: 'myapp' }, format: format.combine( format.label({ label: 'API' }), format.timestamp(), format.printf(({ level, message, label, timestamp }) => { return `${timestamp} [${label}] ${level}: ${message}`; }) ) }) ] }); logger.info('Server started on port 3000'); // Log line in Loki: "2024-01-15T10:30:00.000Z [API] info: Server started on port 3000" logger.debug({ message: 'Request received', labels: { endpoint: '/api/users' } }); // Custom labels are still added even with custom formatting ``` -------------------------------- ### Run Winston-Loki Tests (Shell) Source: https://github.com/janianttonen/winston-loki/blob/development/README.md This command executes the test suite for the `winston-loki` package. It is used to verify the functionality and stability of the library. New tests should be added to the `/test` directory. ```shell npm test ``` -------------------------------- ### Initialize Winston Logger with Loki Transport Source: https://github.com/janianttonen/winston-loki/blob/development/README.md Demonstrates how to configure and instantiate a Winston logger using the LokiTransport. It requires the host URL for the Grafana Loki instance. ```javascript const { createLogger, transports } = require("winston"); const LokiTransport = require("winston-loki"); const options = { transports: [ new LokiTransport({ host: "http://127.0.0.1:3100" }) ] }; const logger = createLogger(options); ``` -------------------------------- ### Log Messages with Custom Labels Source: https://github.com/janianttonen/winston-loki/blob/development/README.md Shows how to attach custom key-value labels to individual log entries when using the Winston logger. ```javascript logger.debug({ message: 'test', labels: { 'key': 'value' } }); ``` -------------------------------- ### Configure Winston-Loki for Grafana Cloud Logging (JavaScript) Source: https://github.com/janianttonen/winston-loki/blob/development/README.md This snippet demonstrates how to configure the Winston-Loki transport to send logs to a Grafana Cloud Loki instance. It requires `LOKI_HOST`, `USER_ID`, and `GRAFANA_CLOUD_TOKEN` which must be obtained from your Grafana Cloud account. The configuration sets up basic authentication and custom labels for log entries. ```javascript const { createLogger, transports } = require("winston"); const LokiTransport = require("winston-loki"); const options = { ..., transports: [ new LokiTransport({ host: 'LOKI_HOST', labels: { app: 'my-app' }, json: true, basicAuth: 'USER_ID:GRAFANA_CLOUD_TOKEN', format: winston.format.json(), replaceTimestamp: true, onConnectionError: (err) => console.error(err), }) ] ... }; const logger = createLogger(options); logger.debug({ message: 'test', labels: { 'key': 'value' } }) ``` -------------------------------- ### Configure Custom HTTP/HTTPS Agents for Winston Loki Source: https://context7.com/janianttonen/winston-loki/llms.txt Shows how to set up custom HTTP and HTTPS agents for Winston Loki to manage advanced networking features like connection pooling, proxy support, and SSL certificate verification. This is useful for specific deployment environments or enhanced network control. ```javascript const winston = require('winston'); const LokiTransport = require('winston-loki'); const https = require('https'); const http = require('http'); // Custom HTTPS agent with keep-alive and connection pooling const httpsAgent = new https.Agent({ keepAlive: true, maxSockets: 10, rejectUnauthorized: true // Verify SSL certificates }); // Custom HTTP agent for local development const httpAgent = new http.Agent({ keepAlive: true, maxSockets: 5 }); const logger = winston.createLogger({ transports: [ new LokiTransport({ host: 'https://loki.example.com:3100', json: true, labels: { job: 'custom-agent-example' }, httpsAgent: httpsAgent, httpAgent: httpAgent }) ] }); logger.info('Using custom HTTP agents for connection pooling'); ``` -------------------------------- ### Use Winston Metadata as Loki Labels (JavaScript) Source: https://context7.com/janianttonen/winston-loki/llms.txt This snippet shows how to automatically convert Winston metadata, including defaultMeta, into Loki labels. It also demonstrates how to exclude specific metadata fields from being converted using the `ignoredMeta` option. The `useWinstonMetaAsLabels` option must be set to `true`. ```javascript const winston = require('winston'); const LokiTransport = require('winston-loki'); const logger = winston.createLogger({ defaultMeta: { service: 'user-service', version: '1.2.3' }, transports: [ new LokiTransport({ host: 'http://127.0.0.1:3100', json: true, useWinstonMetaAsLabels: true, ignoredMeta: ['error_description', 'stack'] // Exclude these from labels }) ] }); // The defaultMeta 'service' and 'version' will be added as Loki labels logger.info('Request processed', { requestId: 'req-123', duration: 45 }); // Labels will include: { level: 'info', service: 'user-service', version: '1.2.3', requestId: 'req-123', duration: '45' } logger.error('Processing failed', { error_description: 'Long error details...' }); // 'error_description' is ignored from labels due to ignoredMeta config ``` -------------------------------- ### Handle Connection Errors with Winston Loki Source: https://context7.com/janianttonen/winston-loki/llms.txt Demonstrates how to configure the `onConnectionError` callback in Winston Loki to gracefully handle connection failures. It logs errors to a fallback file and alerts the monitoring system, with an option to control log retry behavior using `clearOnError`. ```javascript const winston = require('winston'); const LokiTransport = require('winston-loki'); const fs = require('fs'); const logger = winston.createLogger({ transports: [ new LokiTransport({ host: 'http://127.0.0.1:3100', json: true, labels: { job: 'resilient-service' }, clearOnError: false, // Keep logs in batch for retry (default) timeout: 5000, // 5 second timeout onConnectionError: (err) => { // Log to fallback file when Loki is unavailable const timestamp = new Date().toISOString(); fs.appendFileSync('loki-errors.log', `${timestamp}: ${err.message}\n`); // Alert monitoring system console.error('Loki connection failed:', err.message); } }) ] }); logger.info('Application running with error handling configured'); ``` -------------------------------- ### Manually Flush Pending Logs to Loki (JavaScript) Source: https://context7.com/janianttonen/winston-loki/llms.txt This snippet illustrates how to manually trigger the flushing of all batched logs to Loki and wait for confirmation. This is particularly useful for ensuring all logs are sent before an application shuts down or at critical points in the execution flow. The `gracefulShutdown` option should be set to `false` to enable manual control. ```javascript const winston = require('winston'); const LokiTransport = require('winston-loki'); const lokiTransport = new LokiTransport({ host: 'http://127.0.0.1:3100', json: true, batching: true, interval: 30, // Long interval gracefulShutdown: false // Manual control }); const logger = winston.createLogger({ transports: [lokiTransport] }); async function processAndShutdown() { logger.info('Starting batch job'); // Process items for (let i = 0; i < 100; i++) { logger.info(`Processing item ${i}`, { itemId: i }); } logger.info('Batch job completed'); // Flush all pending logs before shutdown await lokiTransport.flush(); console.log('All logs flushed to Loki'); process.exit(0); } processAndShutdown(); ``` -------------------------------- ### Add Custom Labels to Individual Log Entries Source: https://context7.com/janianttonen/winston-loki/llms.txt Illustrates how to attach custom labels to specific log entries when using the LokiTransport. These labels are merged with the globally defined labels in the transport configuration. ```javascript const winston = require('winston'); const LokiTransport = require('winston-loki'); const logger = winston.createLogger({ transports: [ new LokiTransport({ host: 'http://127.0.0.1:3100', json: true, labels: { job: 'api-server', env: 'production' } }) ] }); // Add custom labels to specific log entries logger.info({ message: 'User logged in', labels: { userId: '12345', action: 'login' } }); logger.error({ message: 'Database connection failed', labels: { service: 'postgres', retry: '3' } }); logger.debug({ message: 'Cache hit', labels: { cacheKey: 'user:session:abc' } }); // Output in Loki will have labels: { job: 'api-server', env: 'production', level: 'info', userId: '12345', action: 'login' } ``` -------------------------------- ### Disable Log Batching for Immediate Delivery (JavaScript) Source: https://context7.com/janianttonen/winston-loki/llms.txt This snippet shows how to disable log batching, causing each log to be sent immediately as it's created. This mode is suitable for critical applications where minimizing log delivery latency is paramount. An `onConnectionError` handler is included to manage potential network issues. ```javascript const winston = require('winston'); const LokiTransport = require('winston-loki'); const logger = winston.createLogger({ transports: [ new LokiTransport({ host: 'http://127.0.0.1:3100', json: true, batching: false, // Disable batching - logs sent immediately labels: { job: 'critical-service' }, onConnectionError: (err) => { console.error('Failed to send log:', err.message); // Implement fallback logging here } }) ] }); // Each log is sent immediately to Loki logger.error('Critical system failure detected'); logger.warn('Service degradation occurring'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.