@treeimmersion/logging v1.0.0
@treeimmersion/logging
@treeimmersion/logging
is a lightweight and flexible logging library for Node.js applications, built on top of Pino. It provides structured logging, error tracking, and optimized integration with Datadog to enhance application observability.
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 library via npm:
npm install @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
The logger automatically captures error messages and stack traces:
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-pretty
for 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.js
Full 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
The logger.test.ts
file contains tests to verify the loggerβs functionality. Run tests with:
npm test
Example unit test:
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 anerror
field of roleError
.
export interface LogMeta {
[key: string]: any;
}
export interface LogError extends LogMeta {
error: Error;
}
Best Logging Practices
- Use
info
for normal events anderror
only for actual failures. - Add key metadata to improve traceability.
- Avoid logging sensitive data.
Contributing
Contributions are welcome! To contribute:
- Create a branch for your feature or fix.
- Write tests for your changes.
- Submit a pull request with a clear description of modifications.
π Note: Follow structured logging best practices to maintain high-quality code and observability. π
3 months ago