@bridgera-iot/bridgera-structured-logger
v1.0.35
Published
A lightweight structured logger for Node.js with JSON output to console and file, supporting custom transports.
Readme
Bridgera Structured Logger
A lightweight, structured JSON logger for Node.js that prints logs to console (and optional files via Log4js) and sends critical logs via email using Nodemailer.
Features
- Structured JSON output: Consistent log schema with timestamps, levels, service name, function and file context, plus custom metadata.
- Email notifications: Optional email alerts for
errorlogs (or any level) with customizable thresholds and templates. - Caller identification: Automatically captures the calling function name and source file, skipping internal and third-party frames.
- Flexible control flags: Per-log flags to force email (
sendEmail), silence email (sendEmail: false), or mark critical (critical). - Environment modes: Pretty-printed JSON in
development, compact inproduction.
Installation
npm install bridgera-structured-loggerOr, if you prefer Yarn:
yarn add bridgera-structured-loggerQuick Start
const StructuredLogger = require("bridgera-structured-logger");
// Instantiate with email notifications on errors:
const logger = new StructuredLogger(
"my-service", // serviceName
process.env.NODE_ENV || "development", // env
{
transport: {
host: "smtp.mailtrap.io",
port: 587,
secure: false,
auth: {
user: "your-smtp-user",
pass: "your-smtp-pass",
},
},
from: "[email protected]",
to: "[email protected]",
level: "error", // only send email for `error` and above
subjectTemplate: "{{message}}", // default template uses log message
}
);
// Logging examples:
logger.info("Server started", { port: 3000 });
logger.warn("Cache miss", { key: "user:1234" });
logger.error("Database connection failed", {
errorMessage: err.message,
stackTrace: err.stack,
});Logs will be printed as JSON to the console, and error calls will trigger an email alert.
API Reference
new StructuredLogger(serviceName, env, emailOptions)
serviceName(string, default:"default-service") — Identifier for your application or module.env("development" | "production"; default: "development") — Controls pretty-printing of JSON output.emailOptions(object, optional) — Configuration for email alerts:transport(object) — Nodemailer transport options (host,port,auth, etc.).from(string) — Sender email address.to(string) — Recipient email address.level("error" | "warn" | "info"; default: "error") — Minimum log level that triggers email.subjectTemplate(string; default:"{{message}}") — Template for the email subject. Available tokens:{{service}}— service name{{level}}— log level{{message}}— the log message
.log(level, message, meta)
Low-level log method. Automatically called by the helper methods below.
level("info" | "warn" | "error") — Log severity.message(string) — Main log message.meta(object, optional) — Additional structured data.sendEmail: true|false— Force or suppress email for this call.critical: true— Always send email regardless of level.- Any other custom fields to include in the log JSON.
Convenience Methods
.info(message, meta)— Shorthand forlog('info', message, meta)..warn(message, meta)— Shorthand forlog('warn', message, meta)..error(message, meta)— Shorthand forlog('error', message, meta).
Advanced Configuration
Caller Context
Automatically captures the calling function and file path:
{
"function": "doSomething",
"file": "controllers/myController.js"
}You can customize the skip logic by modifying _getCaller() in index.js if you have additional wrappers to ignore.
Global Error & Rejection Handling
In your application entry point, you can catch process-level errors:
process.on("unhandledRejection", (reason) => {
logger.error("Unhandled Promise Rejection", {
errorMessage: reason.message,
stackTrace: reason.stack,
});
});
process.on("uncaughtException", (err) => {
logger.error("Uncaught Exception", {
errorMessage: err.message,
stackTrace: err.stack,
});
process.exit(1);
});Examples
Force Email on Info
logger.info("Manual alert", { sendEmail: true });Suppress Email on Error
logger.error("Non-critical error", { sendEmail: false });Mark a Warning as Critical
logger.warn("Threshold breached", { critical: true });Testing Locally
Use npm link, npm pack, or file: dependencies to test unpublished changes (see Testing your module locally).
Contributing
- Fork the repo
npm install- Add features or bug fixes
npm test- Submit a pull request
License
MIT © Bridgera IOT Team
