### Install Woodlot using npm or yarn Source: https://github.com/adpushup/woodlot/blob/master/README.md This snippet shows how to install the Woodlot logging utility using either npm or yarn package managers. It adds Woodlot as a dependency to your project. ```bash npm install woodlot --save ``` ```bash yarn add woodlot ``` -------------------------------- ### Combined Log Format Example Source: https://github.com/adpushup/woodlot/blob/master/README.md Example of a log entry in the combined log format. This format extends the common log format by including the User-Agent and Referrer information, providing more context about the client request. ```text 127.0.01 - - [23/Apr/2017:20:48:10 +0000] "GET /api HTTP/1.1" 200 4 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" ``` -------------------------------- ### Common Log Format Example Source: https://github.com/adpushup/woodlot/blob/master/README.md Example of a log entry in the common log format. This format is a standard way to log web server access, typically including IP address, timestamp, request method, URL, and status code. ```text 127.0.01 - - [23/Apr/2017:20:47:28 +0000] "GET /api HTTP/1.1" 200 4 ``` -------------------------------- ### Custom Logger JSON Log Output Example Source: https://github.com/adpushup/woodlot/blob/master/README.md Example of a log entry generated by the `customLogger` when configured with the JSON format. It includes the timestamp, the log message, and the log level. ```json { "timeStamp": "23/Apr/2017:17:02:33 +0000", "message": "Data sent successfully", "level": "INFO" } ``` -------------------------------- ### Custom Logger Initialization with JSON Format Source: https://github.com/adpushup/woodlot/blob/master/README.md Demonstrates how to initialize Woodlot's `customLogger` with specific streams, disabling stdout, and configuring the JSON format with custom spacing and separator. This setup is useful for tailored logging within an Express application. ```javascript var express = require('express'); var app = express(); var woodlotCustomLogger = require('woodlot').customLogger; var woodlot = new woodlotCustomLogger({ streams: ['./logs/custom.log'], stdout: false, format: { type: 'json', options: { spacing: 4, separator: '\n' } } }); app.get('/', function (req, res) { var id = 4533; woodlot.info('User id ' + id + ' accessed'); return res.status(200).send({ userId: id }); }); ``` -------------------------------- ### Custom Logger Text Log Output Example Source: https://github.com/adpushup/woodlot/blob/master/README.md Example of a log entry generated by the `customLogger` when configured with the text format. This format provides a more human-readable output, including the log level, timestamp, and message. ```text INFO [23/Apr/2017:17:02:33 +0000]: "Data sent successfully" ``` -------------------------------- ### JSON Log Format Example Source: https://github.com/adpushup/woodlot/blob/master/README.md Example of a log entry in JSON format. This format can include details like response time, method, URL, IP, and user analytics. Options like `bodyParser` and `cookieParser` can be enabled to log request body and cookies. ```json { "responseTime": "4ms", "method": "GET", "url": "/api", "ip": "127.0.01", "body": {}, "params": {}, "query": {}, "httpVersion": "1.1", "statusCode": 200, "timeStamp": "23/Apr/2017:20:46:01 +0000", "contentType": "text/html; charset=utf-8", "contentLength": "4", "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36", "referrer": null, "userAnalytics": { "browser": "Chrome", "browserVersion": "60.0.3112.90", "os": "Mac OS", "osVersion": "10.11.6", "country": { "name": "India", "isoCode": "IN" } }, "headers": { "host": "localhost:8000", "connection": "keep-alive", "accept-encoding": "gzip, deflate, sdch, br", "accept-language": "en-US,en;q=0.8,la;q=0.6" }, "cookies": { "userId": "zasd-167279192-asknbke-0684" } } ``` -------------------------------- ### Configure Woodlot as an ExpressJS Middleware Source: https://github.com/adpushup/woodlot/blob/master/README.md This example demonstrates how to integrate Woodlot as middleware in an ExpressJS application. It configures logging streams, route filtering, user analytics, and output format. ```javascript var express = require('express'); var app = express(); var woodlot = require('woodlot').middlewareLogger; app.use( woodlot({ streams: ['./logs/app.log'], stdout: false, routes: { whitelist: ['/api', '/dashboard'], strictChecking: false }, userAnalytics: { platform: true, country: true }, format: { type: 'json', options: { cookies: true, headers: true, spacing: 4, separator: '\n' } } }) ); // Your Express app routes here... ``` -------------------------------- ### Custom Logger with Text Format - JavaScript Source: https://context7.com/adpushup/woodlot/llms.txt Shows how to configure and use the custom logger for plain text output. This is useful for simpler log files or direct console output, logging application start, debug, warning, and error messages. ```javascript var woodlotCustomLogger = require('woodlot').customLogger; var logger = new woodlotCustomLogger({ streams: ['./logs/app.txt'], stdout: true, format: { type: 'text', options: { separator: '\n' } } }); logger.info('Application started'); logger.debug('Debug mode enabled'); logger.warn('Memory usage high'); logger.err('Connection failed'); ``` -------------------------------- ### Woodlot Custom Logger Log Levels Source: https://github.com/adpushup/woodlot/blob/master/README.md Examples of using different log levels (info, debug, warn, err) with Woodlot's `customLogger`. These methods allow for categorizing log messages based on their severity or purpose. ```javascript woodlot.info('Data sent successfully'); ``` ```javascript woodlot.debug('Debugging main function'); ``` ```javascript woodlot.warn('User Id is required'); ``` ```javascript woodlot.err('Server error occurred'); ``` -------------------------------- ### Woodlot Route Filtering Example Source: https://github.com/adpushup/woodlot/blob/master/README.md This code snippet illustrates how to configure route filtering for Woodlot's ExpressJS middleware. It shows how to use a whitelist with strict checking enabled or disabled. ```javascript routes: { whitelist: ['/api'], strictChecking: false } ``` -------------------------------- ### Listen to Woodlot Events Source: https://github.com/adpushup/woodlot/blob/master/README.md Demonstrates how to import the Woodlot events module and attach listeners to specific log events. The callback receives the formatted log entry as an argument. ```javascript var woodlotEvents = require('woodlot').events; woodlotEvents.on('reqLog', function (log) { console.log('New log generated'); }); ``` -------------------------------- ### Handle Custom Logger Levels Source: https://github.com/adpushup/woodlot/blob/master/README.md Demonstrates how to listen for specific log levels including info, debug, warn, and err within the custom logger. ```javascript woodlotEvents.on('info', function (log) { console.log('Info log - ' + log); }); woodlotEvents.on('debug', function (log) { console.log('Debug log - ' + log); }); woodlotEvents.on('warn', function (log) { console.log('Warn log - ' + log); }); woodlotEvents.on('err', function (log) { console.log('Error log - ' + log); }); ``` -------------------------------- ### Configure Route Filtering in Woodlot Source: https://context7.com/adpushup/woodlot/llms.txt Demonstrates how to use the whitelist option to filter which routes are logged. It shows both strict matching and non-strict matching configurations. ```javascript var express = require('express'); var woodlot = require('woodlot').middlewareLogger; var app = express(); app.use(woodlot({ streams: ['./logs/api.log'], stdout: true, routes: { whitelist: ['/api'], strictChecking: false }, format: { type: 'json' } })); app.get('/api/users', function(req, res) { res.json({ users: [] }); }); app.listen(3000); ``` -------------------------------- ### Custom Logger with JSON Format - JavaScript Source: https://context7.com/adpushup/woodlot/llms.txt Demonstrates initializing and using the custom logger with JSON output format. It logs application events like user access and server errors to a specified file and console. ```javascript var express = require('express'); var woodlotCustomLogger = require('woodlot').customLogger; var app = express(); // Initialize custom logger var logger = new woodlotCustomLogger({ streams: ['./logs/custom.log'], stdout: true, format: { type: 'json', options: { spacing: 4, separator: '\n' } } }); app.get('/users/:id', function(req, res) { var userId = req.params.id; logger.info('User ' + userId + ' accessed their profile'); // Simulate database lookup var user = { id: userId, name: 'John Doe' }; if (!user) { logger.warn('User ' + userId + ' not found'); return res.status(404).json({ error: 'User not found' }); } logger.debug('Retrieved user data: ' + JSON.stringify(user)); res.json(user); }); app.use(function(err, req, res, next) { logger.err('Server error: ' + err.message); res.status(500).json({ error: 'Internal server error' }); }); app.listen(3000); ``` -------------------------------- ### Events API for Request Logging - JavaScript Source: https://context7.com/adpushup/woodlot/llms.txt Illustrates using Woodlot's middleware logger and events API to capture and react to HTTP request logs. It demonstrates listening for all requests, specific status codes (200, 404, 500), and general errors. ```javascript var express = require('express'); var woodlot = require('woodlot').middlewareLogger; var woodlotEvents = require('woodlot').events; var app = express(); app.use(woodlot({ streams: ['./logs/app.log'], stdout: false, format: { type: 'json' } })); // Listen to all request logs woodlotEvents.on('reqLog', function(log) { console.log('Request logged:', log.url, '-', log.statusCode); // Send to external monitoring service }); // Listen to specific status codes woodlotEvents.on('200', function(log) { console.log('Success:', log.method, log.url); }); woodlotEvents.on('404', function(log) { console.log('Not Found:', log.url); // Alert monitoring system }); woodlotEvents.on('500', function(log) { console.log('Server Error:', log.url); // Send alert notification }); // Listen to all error responses (status >= 400) woodlotEvents.on('reqErr', function(log) { console.log('Request Error:', log.statusCode, log.url); // Log to error tracking service }); app.get('/api/data', function(req, res) { res.json({ data: 'success' }); }); app.listen(3000); ``` -------------------------------- ### Handle Middleware Request Logs Source: https://github.com/adpushup/woodlot/blob/master/README.md Shows how to capture standard request logs and specific HTTP status code events using the middlewareLogger. ```javascript woodlotEvents.on('reqLog', function (log) { console.log('The following log entry was added - \n' + log); }); woodlotEvents.on('200', function (log) { console.log('Success!'); }); woodlotEvents.on('403', function (log) { console.log('Request forbidden!'); }); ``` -------------------------------- ### Write Logs to Multiple File Streams Source: https://context7.com/adpushup/woodlot/llms.txt Shows how to configure Woodlot to write log entries to multiple file paths simultaneously. This is useful for redundancy or separating logs for different monitoring tools. ```javascript var express = require('express'); var woodlot = require('woodlot').middlewareLogger; var app = express(); app.use(woodlot({ streams: [ './logs/app.log', './logs/backup.log', '/var/log/myapp/access.log' ], stdout: true, format: { type: 'json', options: { spacing: 2, separator: '\n' } } })); app.get('/', function(req, res) { res.send('Hello World'); }); app.listen(3000); ``` -------------------------------- ### Configure Woodlot for Apache Combined Log Format Source: https://context7.com/adpushup/woodlot/llms.txt This snippet configures the Woodlot middleware to output logs in the Apache Combined format, which includes additional referrer and user agent information. ```javascript var express = require('express'); var woodlot = require('woodlot').middlewareLogger; var app = express(); app.use(woodlot({ streams: ['./logs/combined.log'], stdout: true, format: { type: 'combined', options: { separator: '\n' } } })); app.get('/api', function(req, res) { res.status(200).send('OK'); }); app.listen(3000); ``` -------------------------------- ### Configure Woodlot Middleware for JSON Logging Source: https://context7.com/adpushup/woodlot/llms.txt This snippet demonstrates how to integrate Woodlot middleware into an ExpressJS application to log HTTP requests in JSON format. It includes configuration for file streams, route filtering, and user analytics. ```javascript var express = require('express'); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var woodlot = require('woodlot').middlewareLogger; var app = express(); app.use(bodyParser.json()); app.use(cookieParser()); app.use(woodlot({ streams: ['./logs/app.log', './logs/backup.log'], stdout: true, routes: { whitelist: ['/api', '/dashboard'], strictChecking: false }, userAnalytics: { platform: true, country: true }, format: { type: 'json', options: { cookies: true, headers: true, spacing: 4, separator: '\n' } } })); app.get('/api/users', function(req, res) { res.json({ users: ['alice', 'bob'] }); }); app.listen(3000); ``` -------------------------------- ### Enable Compact JSON Logging Source: https://context7.com/adpushup/woodlot/llms.txt Configures Woodlot to output logs in a single-line compact JSON format. This is ideal for log aggregation systems that process one log entry per line. ```javascript var express = require('express'); var woodlot = require('woodlot').middlewareLogger; var app = express(); app.use(woodlot({ streams: ['./logs/compact.log'], stdout: true, format: { type: 'json', options: { compact: true, headers: false, separator: '\n' } } })); app.get('/api', function(req, res) { res.json({ status: 'ok' }); }); app.listen(3000); ``` -------------------------------- ### Configure Woodlot for Apache Common Log Format Source: https://context7.com/adpushup/woodlot/llms.txt This snippet configures the Woodlot middleware to output logs in the standard Apache Common format, suitable for traditional log analysis tools. ```javascript var express = require('express'); var woodlot = require('woodlot').middlewareLogger; var app = express(); app.use(woodlot({ streams: ['./logs/access.log'], stdout: true, format: { type: 'common', options: { separator: '\n' } } })); app.get('/api', function(req, res) { res.status(200).send('OK'); }); app.listen(3000); ``` -------------------------------- ### Events API for Custom Logger - JavaScript Source: https://context7.com/adpushup/woodlot/llms.txt Explains how to use the events API to monitor application-level log entries generated by the custom logger. It shows how to subscribe to specific log levels (info, debug, warn, err) and react accordingly. ```javascript var woodlotCustomLogger = require('woodlot').customLogger; var woodlotEvents = require('woodlot').events; var logger = new woodlotCustomLogger({ streams: ['./logs/custom.log'], stdout: false, format: { type: 'json' } }); // Listen to info level logs woodlotEvents.on('info', function(log) { console.log('INFO:', log.message); }); // Listen to debug level logs woodlotEvents.on('debug', function(log) { console.log('DEBUG:', log.message); }); // Listen to warning level logs woodlotEvents.on('warn', function(log) { console.log('WARNING:', log.message); // Send to monitoring dashboard }); // Listen to error level logs woodlotEvents.on('err', function(log) { console.log('ERROR:', log.message); // Send alert, notify on-call engineer }); // Application logging logger.info('Service initialized'); logger.debug('Loading configuration from disk'); logger.warn('Cache miss rate exceeding threshold'); logger.err('Database connection pool exhausted'); ``` -------------------------------- ### Events API - Request Logging Source: https://context7.com/adpushup/woodlot/llms.txt Woodlot emits events for HTTP requests, enabling real-time monitoring and integration with external logging or alerting services. ```APIDOC ## Events API - Request Logging ### Description Subscribe to request lifecycle events to monitor traffic and handle errors dynamically. ### Supported Events - **reqLog**: Fires for every incoming HTTP request. - **[status_code]**: Fires when a specific HTTP status code is returned (e.g., '200', '404', '500'). - **reqErr**: Fires for any request resulting in a status code >= 400. ### Usage Example woodlotEvents.on('reqLog', function(log) { console.log('Request logged:', log.url, '-', log.statusCode); }); ``` -------------------------------- ### Events API - Custom Logger Events Source: https://context7.com/adpushup/woodlot/llms.txt Monitor application-level log entries by subscribing to specific log severity levels. ```APIDOC ## Events API - Custom Logger Events ### Description Allows developers to hook into specific log levels to trigger alerts or update monitoring dashboards. ### Supported Levels - **info**: Informational messages. - **debug**: Debugging details. - **warn**: Warning messages. - **err**: Error messages. ### Usage Example woodlotEvents.on('err', function(log) { console.log('ERROR:', log.message); }); ``` -------------------------------- ### Custom Logger API Source: https://context7.com/adpushup/woodlot/llms.txt The customLogger class allows developers to log application-specific messages with defined severity levels (info, debug, warn, err) to configured streams. ```APIDOC ## Custom Logger Initialization ### Description Initializes a custom logger instance to handle application-level logging to files or standard output. ### Parameters #### Options - **streams** (array) - Required - List of file paths for log output. - **stdout** (boolean) - Optional - Whether to log to standard output. - **format** (object) - Optional - Configuration for log formatting (type: 'json' or 'text'). ### Request Example new woodlotCustomLogger({ streams: ['./logs/custom.log'], stdout: true, format: { type: 'json' } }); ``` -------------------------------- ### Handle Request Errors Source: https://github.com/adpushup/woodlot/blob/master/README.md Captures errors from requests, defined as any response with a status code of 400 or higher. ```javascript woodlotEvents.on('reqErr', function (log) { console.log('Errored!'); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.