///
This page provides a collection of practical code examples demonstrating various features and common use cases of Zario. Each example includes the full, working code from the repository's `examples/`
51 views
~51 views from guests
Guest views are estimated from total page views. These include anonymous visitors and users who weren't logged in when they viewed the page.
This page provides a collection of practical code examples demonstrating various features and common use cases of Zario. Each example includes the full, working code from the repository's examples/ directory, along with explanations to help you understand how to leverage Zario in your Node.js applications.
For installation instructions and a quick overview, refer to the [Getting Started] page. For detailed information on Zario's classes and interfaces, see the [API Reference].
This example demonstrates the fundamental aspects of Zario: initializing a logger, emitting various log levels, dynamically switching output formats, and using prefixes.
Logger instance is created with:
level: "info": Only messages with severity info or higher (like warn, error) will be processed. debug, boring, and silent will be ignored by this logger.colorize: true: Enables ANSI color codes for console output.json: false: Defaults to human-readable text output.transports: An array containing ConsoleTransport (output to console) and FileTransport (output to ./logs/app.log). Refer to [Transports] for more details.timestampFormat: Customizes the timestamp display.info(), warn(), error(), debug(), boring(), and silent() are demonstrated. Note that debug, boring, and silent messages won't appear with the logger's initial level: "info".logger.setFormat("json"): The logger's output format is dynamically changed to JSON.logger.info("User login", { userId: 42, ip: "127.0.0.1" }): This message will be logged as a structured JSON object, including the provided metadata.logger.setFormat("text"): The format is switched back to text.prefixedLogger is created with prefix: "[WebApp]" and timestamp: true. All its messages will include this prefix and a timestamp.Logger.global.info("Something global happened") shows how to access a globally shared logger instance, useful for quick, unconfigured logging or in small scripts.This example highlights Zario's asyncMode feature, which performs log I/O operations in the background, preventing them from blocking your main application thread. This is crucial for high-performance applications.
asyncMode: true: The asyncLogger is configured with asyncMode: true, instructing Zario to perform Transport writes non-blockingly. This is particularly beneficial for FileTransport and HttpTransport which involve I/O.console.log("Main thread continues immediately...") statement is executed almost instantly, demonstrating that logging operations do not block the main thread.asyncMode: The setAsyncMode() method allows you to toggle this behavior at runtime, useful for debugging (sync mode) vs. production (async mode).createChild() automatically inherit the asyncMode setting from their parent, ensuring consistent behavior across related loggers.This example focuses on generating structured JSON log output, which is highly recommended for production environments. JSON logs are easily parseable by log aggregation systems (e.g., Splunk, ELK Stack, DataDog) for analysis, monitoring, and alerting.
json: true: The jsonLogger is configured to output logs in JSON format. This means all log messages, along with their level, message, timestamp, prefix (if any), and metadata, will be serialized into a single JSON string.info, error, warn) is called with a message and an arbitrary object containing metadata. This metadata is automatically included as fields in the resulting JSON object, making your logs contextually rich and queryable.ConsoleTransport (which will display JSON strings) and FileTransport (writing JSON lines to json-logs.json).The output in json-logs.json will look something like this (formatted for readability):
This example demonstrates how to integrate Zario with an Express.js server, particularly focusing on creating request-scoped child loggers to provide granular context for each incoming HTTP request.
logger instance is created for general server events, with a [ExpressServer] prefix.logger Type Declaration: A declaration merges a logger: Logger property into Express's Request interface, allowing TypeScript to recognize req.logger.app.use()) intercepts all incoming requests.logger.createChild() is called to create a new Logger instance. This child logger inherits all settings from the parent but adds a dynamic prefix (e.g., [GET /]) relevant to the current request.req.logger, making it accessible throughout the request lifecycle.req.logger.info("Request received") logs the initial request.app.get('/'), app.get('/users')), req.logger is used to emit messages specific to that request context. These logs will automatically include the request-specific prefix.This pattern ensures that all logs related to a single HTTP request are easily identifiable and contextualized, simplifying debugging and tracing in a busy server environment.
Similar to the Express.js example, this demonstrates Zario's integration with a Fastify server, focusing on setting up request-scoped child loggers for enhanced request context in logs.
logger instance is created for general server events, with a [FastifyServer] prefix.fastify.decorate('logger', logger) adds the base logger to the Fastify instance itself.declare module 'fastify' { ... } extends Fastify's type definitions to include logger: Logger on both FastifyInstance and FastifyRequest, providing TypeScript safety.onRequest Hook:
onRequest hook is used to intercept incoming requests, similar to Express.js middleware.logger.createChild() creates a request-specific logger with a dynamic prefix (e.g., [GET /]).req.logger, making it available throughout the request.req.logger.info('Incoming request') logs the start of the request.fastify.get('/'), fastify.get('/error')), req.logger is used for request-specific logging. These logs will inherit the request's unique prefix and any context defined.start() function uses the base logger to log server startup and any potential errors during initialization.This setup ensures that all logs for a given Fastify request are easily traceable, leveraging Zario's child logger functionality for contextual logging.
This example demonstrates how to implement request-scoped logging using Zario with a plain Node.js http server, without relying on web frameworks like Express or Fastify. This illustrates the core concept of associating logs with individual requests.
logger is initialized for server-level messages, with a [HTTP] prefix.http.createServer Callback:
requestId is generated.logger.createChild() creates a new requestLogger. This child logger adds a dynamic prefix (e.g., [GET /]) reflecting the request's method and URL, and includes the requestId in its context.requestLogger is then used throughout the handling of that specific request.requestLogger.info("Incoming request") marks the beginning of request processing.try...catch block, the requestLogger is used to log success (Request completed successfully) or failure (Request failed).requestLogger will automatically include the [${req.method} ${req.url}] prefix and the requestId context, making it easy to trace individual requests.This example demonstrates how to implement request-scoped logging manually in a Node.js HTTP server, providing clear and contextualized log trails for each client interaction.