@treeimmersion/logging
v1.0.1
Published
A lightweight logging library for Node.js
Downloads
6
Maintainers
Readme
@treeimmersion/logging
@treeimmersion/logging is a high-performance logging library for NodeJS applications, developed by Tree Immersion Technologies to provide structured and efficient log management.
Built on top of Pino, this library ensures lightweight logging, error tracking, and seamless integration with monitoring tools like Datadog, enhancing application observability and debugging capabilities.
Designed for scalability and performance, @treeimmersion/logging is the ideal choice for modern applications that require reliable and structured log management.
🔥 Key Features
- 🚀 Lightweight & Fast: Built on Pino, ensuring high performance with minimal resource consumption.
- 📊 Structured Logging: Enhances traceability and analysis with well-organized logs.
- 🔧 Adaptive Configuration: Automatically adjusts log formats based on the environment (development or production).
- 📡 Datadog Integration: Tags active spans with relevant error and stack trace information.
- 🎨 Customizable Format: Allows inclusion of specific metadata on operations and states.
🚀 Installation
Install the package using npm:
npm install @treeimmersion/loggingOr using yarn:
yarn add @treeimmersion/logging📌 Usage
Available Methods
The logger provides three primary methods (info, error, debug), each requiring the following parameters:
- message (
string): Main log message. - operation (
string): Name of the ongoing operation. - status (
string): Operation status (success,failure, etc.). - meta (
LogMeta | LogError): Additional data providing operation context.
Example: Logging Information
import logger from '@treeimmersion/logging';
logger.info('Operation completed', 'register', 'success', {
username: 'tm2600',
name: 'TM 2600',
role: 'admin',
});Example: Logging Errors
try {
throw new Error('Not found');
} catch (error) {
logger.error('Record not found', 'searchUser', 'failure', {
error,
username: 'tm2600',
role: 'admin',
});
}⚙️ Configuration
Automatic Mode Based on Environment
- Development Mode: Uses
pino-prettyfor more readable logs. - Production Mode: Emits logs in JSON format, ideal for tools like Datadog or ELK.
Advanced Configuration in config.ts
Modify the default logger settings, such as log level and output format, in the config.ts file.
export const LOG_LEVEL = process.env.LOG_LEVEL || 'info';
export const LOG_FORMAT = process.env.LOG_FORMAT || 'json';Customizing Log Format in formatters.ts
The formatters.ts file allows modifications to log structure. For example, you can add custom timestamps or change the output format.
export const formatLog = (message: string, level: string) => {
return `${new Date().toISOString()} [${level.toUpperCase()}]: ${message}`;
};Datadog APM Integration
If an active span is detected in Datadog, captured errors are automatically tagged:
import tracer from 'dd-trace';
import logger from '@treeimmersion/logging';
try {
throw new Error('Service failure');
} catch (error) {
const span = tracer.scope().active();
logger.error('Request error', 'service_request', 'failure', { error });
if (span) {
span.setTag('error.message', error.message);
span.setTag('error.stack', error.stack);
}
}Setting Log Levels
Define the logging level using the LOG_LEVEL environment variable:
LOG_LEVEL=debug node app.jsFull Example with Express
import express from 'express';
import logger from '@treeimmersion/logging';
const app = express();
app.use(express.json());
app.post('/register', (req, res) => {
const { username, name, role } = req.body;
try {
const result = { enable: true, success: true };
logger.info('Register successful', 'register', 'success', {
username,
name,
role,
result,
});
res.status(200).json(result);
} catch (error) {
logger.error('Register failed', 'register', 'failure', {
error,
username,
name,
role,
});
res.status(500).json({ message: 'Register error' });
}
});
app.listen(3000, () => {
logger.info('Server running on port 3000', 'server_start', 'success');
});Unit Testing
Run tests with:
npm testExample:
test('Should log an info message', () => {
const logSpy = jest.spyOn(console, 'log');
logger.info('Test message', 'test_operation', 'success');
expect(logSpy).toHaveBeenCalled();
logSpy.mockRestore();
});Custom Types
- LogMeta: Defines additional metadata for logs.
- LogError: Extends
LogMeta, including anerrorfield of roleError.
export interface LogMeta {
[key: string]: any;
}
export interface LogError extends LogMeta {
error: Error;
}Best Logging Practices
- Use
infofor normal events anderroronly for actual failures. - Add key metadata to improve traceability.
- Avoid logging sensitive data.
📜 License
This project is licensed under the MIT License.
© 2025 Tree Immersion Technologies. All rights reserved.
