如何在Node.js Bunyan日志中添加自定义JSON对象?
Hey there! No worries at all about asking basic questions—we all start somewhere with new tools. Let's break down your Bunyan questions step by step:
1. Confirming JSON Stream Output to File
First off, your current code is already doing exactly what you want: streaming JSON-formatted logs to your bunayan.log file. Bunyan's default behavior is to output logs as newline-delimited JSON objects, which is why you're seeing that {"name":"testApp",...} structure in your file. That's the expected format—great job getting that set up!
For your future plan to push logs to a remote host, you can extend the streams array with additional stream configurations (like a TCP or HTTP stream), but we can circle back to that once you're ready.
2. Adding Custom JSON Objects to Bunyan Logs
There are a few flexible ways to include custom JSON data in your logs, depending on whether you want the fields to apply to all logs or just specific ones:
Option 1: Add Custom Fields to Individual Log Entries
You can pass a custom JSON object as the first argument to any Bunyan log method (like info, warn, etc.), followed by your log message. Bunyan will merge this object with its default log fields:
var bunyan = require("bunyan"); var logger = bunyan.createLogger({ name: "testApp", streams: [ { path: "bunayan.log" } ], src: true }); // Add custom JSON to a single info log logger.info({ user_id: 123, request_path: "/api/data", response_status: 200 }, "Data sent to file");
This will produce a log entry like:
{"name":"testApp","user_id":123,"request_path":"/api/data","response_status":200,"msg":"Data sent to file",...}
Option 2: Add Global Custom Fields to All Logs
If you want certain custom fields to appear in every log entry from your logger, define them in the fields option when creating the logger:
var logger = bunyan.createLogger({ name: "testApp", streams: [ { path: "bunayan.log" } ], src: true, // Global custom fields for all logs fields: { service_name: "user-authentication", environment: "development" } }); logger.info("Data sent to file");
Now every log entry will include service_name and environment alongside Bunyan's default fields.
Option 3: Create a Child Logger with Additional Custom Fields
If you need to add context-specific fields (like a request ID for a single API request) without modifying the parent logger, use logger.child() to create a child logger. Child loggers inherit all fields from the parent and add their own:
var parentLogger = bunyan.createLogger({ name: "testApp", streams: [ { path: "bunayan.log" } ], src: true }); // Create a child logger for a specific request var requestLogger = parentLogger.child({ request_id: "abc-123-xyz" }); requestLogger.info("Data sent to file for request");
The resulting log will include the parent's fields plus request_id.
内容的提问来源于stack exchange,提问作者saz

