@jalik/logger
![npm](https://img.shields.io/npm/dt/@jalik/logger.svg)
Easy and customizable logging for your apps.
Features
- Enabling/disabling logging anytime
- Naming of the logger
- Filtering of log events using a custom function
- Support multiple outputs (works sequentially)
- Customizing format of log events
- Ability to pass a context for each log event
- Ability to set a default context for log events
- Use of standards logging levels (debug, info, warning, error, fatal)
Sandbox
Play with the lib here:
https://codesandbox.io/s/jalik-logger-default-example-75o5hx
Creating a logger
import { Logger } from '@jalik/logger';
const logger = new Logger();
Which is equivalent to a production default setup:
import {
Logger,
INFO
} from '@jalik/logger';
const logger = new Logger({
active: true,
level: INFO,
name: 'logger_123456789',
outputs: [
consoleOutput()
]
});
Logging levels
The following levels are available (ordered from the less important to the most
important).
debug
: used for debugging messagesinfo
: used for informational messageswarn
: used for warning messageserror
: used for error messagesfatal
: used for fatal error messages
They can be imported individually.
import {
DEBUG,
INFO,
WARN,
ERROR,
FATAL
} from '@jalik/logger';
Or they can be imported as an array.
import { levels } from '@jalik/logger';
Logging messages
debug(message: string, context?: any)
import { Logger } from '@jalik/logger';
const logger = new Logger({ name: 'main' });
const a = 2;
const b = 4;
const result = a + b;
logger.debug(`result = ${result}`, { a, b });
logger.debug(`result = ${result}`);
info(message: string, context?: any)
import { Logger } from '@jalik/logger';
const logger = new Logger({ name: 'main' });
const bootTime = 1337;
logger.info(`Application started in ${bootTime} ms`, { bootTime, tags: ['boot'] });
logger.info(`Application started in ${bootTime} ms`);
warn(message: string, context?: any)
import { Logger } from '@jalik/logger';
const logger = new Logger({ name: 'main' });
const diskUsage = 93.6;
logger.warn('Disk usage is above 90%', { diskUsage });
logger.warn('Disk usage is above 90%');
error(message: string, context?: any)
import { Logger } from '@jalik/logger';
const logger = new Logger({ name: 'main' });
const error = new Error('Forbidden');
logger.error('Forbidden', { error });
logger.error('Forbidden');
logger.error(error);
fatal(message: string, context?: any)
import { Logger } from '@jalik/logger';
const logger = new Logger({ name: 'main' });
const error = new Error('app crashed');
logger.fatal('app crashed', { error });
logger.fatal('app crashed');
logger.fatal(error);
log(level: string, message: string, context?: any)
This is the "low level" function called by other logging functions.
import {
Logger,
INFO
} from '@jalik/logger';
const logger = new Logger({ name: 'main' });
const ipAddress = '6.6.6.6';
logger.log(INFO, `The IP address ${ipAddress} has failed to login 3 times`, { ipAddress });
Enabling or disabling logging
Logging is enabled by default if you don't set active: false
in Logger options. However, you can
change logging status at anytime with the setActive(boolean)
method.
setActive(boolean)
import { Logger } from '@jalik/logger';
const logger = new Logger({
active: process.env.NODE_ENV === 'PRODUCTION'
});
logger.isActive();
setTimeout(() => {
logger.setActive(false);
logger.info('Sky is blue');
}, 30000)
isActive(): boolean
This method tells you if the logger is enabled.
Setting a default context
It is possible to set defaultContext
when creating the logger.
This context will be passed to all log events and may be overridden for each log.
import { Logger } from '@jalik/logger';
const logger = new Logger({
defaultContext: {
host: process.env.HOST
}
});
logger.info('Application started.');
logger.info('Something happened', { tag: 'something-event' });
Filtering log events
You can filter the logs that are processed by using the filter
option when creating a logger.
import {
DEBUG,
Logger
} from '@jalik/logger';
const cronFilter = (event) => {
return (event.context && event.context.tag === 'cron') || /cron/g.test(event.message)
}
const logger = new Logger({
level: DEBUG,
filter: cronFilter
});
logger.info('Cron jobs executed.', { tag: 'cron' });
logger.info('Application started.');
Logging outputs
A logger can be configured with several outputs
, all of them are executed sequentially.
By default, a logger is configured to output messages to the console with consoleOutput()
.
consoleOutput(options)
The console output displays logs in the console (browser and nodejs).
import {
Logger,
consoleOutput
} from '@jalik/logger';
const logger = new Logger({
name: 'main',
outputs: [
consoleOutput(),
],
});
logger.info('Hello World', { number: 42 });
By default, consoleOutput()
uses the defaultFormatter()
function to format log events, but you can provide your own formatter.
import {
Logger,
consoleOutput,
} from '@jalik/logger';
function customFormatter(event) {
const { level, logger, message } = event;
return [level.toUpperCase(), `[${logger}]`, ':', message].join(' ');
}
const logger = new Logger({
name: 'main',
outputs: [
consoleOutput({ formatter: customFormatter }),
],
});
logger.info('Hello World', { number: 42 });
fileOutput(options)
The file output writes log events to a file, so it can only be used on NodeJS.
import { Logger,} from '@jalik/logger';
import fileOutput from '@jalik/logger/dist/outputs/fileOutput.js'
const logger = new Logger({
name: 'main',
outputs: [
fileOutput({
path: 'logs.txt',
formatter: JSON.stringify,
flushInterval: 1000
}),
],
});
logger.info('Hello World', { number: 42 });
Changelog
History of releases is in the changelog on github.
License
The code is released under the MIT License.
If you find this lib useful and would like to support my work, donations are welcome :)
![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)