Security News
Bun 1.2 Released with 90% Node.js Compatibility and Built-in S3 Object Support
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
bs-logger is a versatile logging library for Node.js applications. It provides a flexible and configurable logging system that can be easily integrated into various types of projects. The library supports different log levels, custom formats, and transports, making it suitable for both simple and complex logging needs.
Basic Logging
This feature allows you to create a basic logger and log messages at different levels such as info and error.
const { createLogger } = require('bs-logger');
const logger = createLogger();
logger.info('This is an info message');
logger.error('This is an error message');
Custom Log Levels
This feature allows you to set custom log levels, enabling more granular control over what gets logged.
const { createLogger, LogLevels } = require('bs-logger');
const logger = createLogger({ level: LogLevels.debug });
logger.debug('This is a debug message');
logger.warn('This is a warning message');
Custom Transports
This feature allows you to configure multiple transports for logging, such as logging to both console and files.
const { createLogger, transports } = require('bs-logger');
const logger = createLogger({
transports: [
new transports.Console(),
new transports.File({ filename: 'combined.log' })
]
});
logger.info('This message will be logged to both console and file');
Custom Formats
This feature allows you to define custom formats for your log messages, making it easier to read and analyze logs.
const { createLogger, format } = require('bs-logger');
const logger = createLogger({
format: format.combine(
format.timestamp(),
format.printf(({ level, message, timestamp }) => {
return `${timestamp} [${level}]: ${message}`;
})
)
});
logger.info('This is a formatted info message');
Winston is a popular logging library for Node.js that offers similar functionalities to bs-logger, such as multiple transports, custom log levels, and formats. It is widely used and has a large community, making it a reliable choice for logging needs.
Bunyan is another logging library for Node.js that focuses on JSON logging. It provides features like log levels, streams, and serializers. Bunyan is known for its performance and ease of use, especially in applications that require structured logging.
Pino is a fast and low-overhead logging library for Node.js. It offers high performance and supports features like log levels, transports, and serializers. Pino is designed for applications that need to handle a large volume of log messages efficiently.
Opinionated bare simple logger for NodeJS (with TypeScript typings).
BSLogger has been created after being disapointed not finding a matching logger on the internet. Not that others aren't good, they just did not fit what I was looking for.
Here is what I was looking for (and tried to implemented in BSLogger):
child
method)ENV
vars can be used)stderr
Install:
npm install --save bs-logger
# or
yarn add bs-logger
Use:
const { logger } = require('bs-logger');
// or
// import logger from 'bs-logger';
// or
// import { logger } from 'bs-logger';
// as default exports the logger
logger('foo');
logger.debug('bar');
logger.warn({foo: 'bar'}, 'dummy', 'other'/*, ...*/);
More complex example:
// env MY_LOG_TARGETS="debug.log:trace,stderr:warn%json"
import { createLogger } from 'bs-logger';
const logger = createLogger({
context: {namespace: 'http'},
targets: process.env.MY_LOG_TARGETS,
translate: (m) => {
if (process.env.NODE_ENV === 'production') {
m.context = { ...m.context, secret: null };
}
return m;
},
});
// [...]
logger.debug({secret: 'xyz'}, 'trying to login')
// will log into debug.log `trying to login` with secret in the context except in prod
const login = logger.wrap(function login() {
// your login code
})
// [...]
login();
// will log `calling login` with the arguments in context
BSLogger exports a global logger lazyly created on first use, but it is advised to create your own using the createLogger()
helper:
If you are using it in a library wich is meant to be re-distributed:
import { createLogger, LogContexts } 'bs-logger';
const logger = createLogger({ [LogContexts.package]: 'my-pacakge' });
If you are using it in an application of your own:
import { createLogger, LogContexts } 'bs-logger';
const logger = createLogger({ [LogContexts.application]: 'my-app' });
Child loggers extends the context, targets and message translators from their parent. You create a child logger using the child
method:
const childLogger = logger.child({ [LogContexts.namespace]: 'http' })
// childLogger becomes a new logger
Any helper to log within BSLogger is a function which has the same signature as console.log()
, and also accepts an optional first argument being the context. A context is any object
, with some specific (but optional) properties which we'll see later.
logMethod(message: string, ...args: any[]): void
// or
logMethod(context: LogContext, message: string, ...args: any[]): void
You can log using any logger as a function directly (if the logger or its possible parent(s) has not been created with any log level in its context, no level will be attached):
import { createLogger } from 'bs-logger'
const logger = createLogger()
// [...]
logger('my message');
BSLogger is aware of 6 log levels (trace
, debug
, info
, warn
, error
and fatal
) but you can create your owns. A log level is basically a number. The higher it is, the more important will be the message. You can find log levels constants in LogLevels
export:
import { LogLevels } from 'bs-logger';
const traceLevelValue = LogLevels.trace;
const debugLevelValue = LogLevels.debug;
// etc.
For each log level listed above, a logger will have a helper method to directly log using this level:
import { createLogger } from 'bs-logger'
const logger = createLogger()
// [...]
logger.trace('foo')
logger.debug('bar')
// etc.
Those helpers are the equivalent to
logger({ [LogContexts.logLevel]: level }, 'foo')
...except that they'll be replaced with an empty function on the first call if their level will not be handled by any target.
Each logger has a wrap
method which you can use to wrap a function. If there is no matching log target, the wrap
method will simply return your function, else it'll wrap it in another function of same signature. The wrapper will, before calling your function, log a message with received arguments in the context.
// With `F` being the type of your funciton:
logger.wrap(func: F): F
// or
logger.wrap(message: string, func: F): F
// or
logger.wrap(context: LogContext, messages: string, func: F): F
Each root logger (created using createLogger
helper) is attached to 0 or more "target". A target is responsible of writing a log entry somewhere. It is an object with the following properties:
string
: The minimum log level this target's strem writer will be called for{ write: (str: string) => void }
: An object with a write function (like node's stream.Writable
) which will be used to write log entries(msg: LogMessage) => string
: A formatter which will be used to transform a log entry (message object) into a stringWhen using the global logger, or if no targets
specified when creating a logger, calling log methods will output to STDERR anything which has log level higher or equal to warn
. This can be modified as follow by defineing the LOG_TARGETS
environment variable or passing the targets
option to createLogger
. The targets
can be an array of LogTarget
(see above) or a string
defining a list of one or more targets separated by comma (,
). A string
target is composed as follow:
stdout
or stderr
strings (case insensitive). When giving a path to a file, if it ends with the plus sign (+
) the log data will be appended to the file instead of re-creating the file for each run.:
). It should be a number
or the log level name (ie trace
, error
, ...).%
). There are 2 included formatter: json
(used for files by default) and simple
(used for stdout
and stderr
by default). See below to define your own.Examples:
debug.log%simple,stdout:fatal
debug.log
file in CWD dir (re-creates the file for each run). Uses the simple
formatter.fatal
to the standard out.errors.log+:error,debug.log:15
error
to errors.log
file (without re-creating the file at each run).debug.log
file (re-creates the file for each run).A custom formatter is a function that takes a LogMessage
object and returns a string
. It can be registered giving it a name using the registerLogFormatter
helper:
import { registerLogFormatter, createLogger } from 'bs-logger';
registerLogFormatter('foo', m => `${m.sequence} ${new Date(m.tim).toLocaleString()} ${m.message}`);
const logger = createLogger({
targets: 'stdout%foo', // specifying out formatter
});
The whole testing
namespace has useful helpers for using BSLogger while unit testing your product.
In your tests you would usually prefer not having any logging to happen, or you would like to check what has been logged but without actually logging it to any target.
The testing
namespace holds all testing utilities:
import { testing } from 'bs-logger'
testing.setup()
and the logger
(or default
) export will become a LoggerMock
instance (see below).
createLogger
, when testing use the testing.createLoggerMock
instead. It accepts the same first argument, with an extra second argument, optional, being the LogTargetMock
to be used (see below).Loggers created using the testing
namespace will have one and only one log target being a LogTargetMock
, and that target will be set on the target
extra property of the logger.
Here are the extra properties of LogTargetMock
which you can then use for testing:
LogMessage[]
: all log message objects which would have normally be logged
LogMessage
: the last one being loggedLogMessage[]
: all log message objects with trace
level
LogMessage
: last one with trace
levelLogMessage[]
: all log message objects with debug
level
LogMessage
: last one with debug
levelstring[]
: all formatted log message lines which would have normally be logged
string
: the last one being loggedstring[]
: all formatted log message lines with trace
level
string
: last one with trace
levelstring[]
: all formatted log message lines with debug
level
string
: last one with debug
level() => void
: method to clear all log message objects and formatted lines(level: number | null, untilLevel?: number) => LogMessage[]
: method to filter log message objects(level: number | null, untilLevel?: number) => string[]
: method to filter formatted log message linesLet's say you have a logger.js
file in which you create the logger for your app:
// file: logger.js
import { testing, createLogger, LogContexts } from 'bs-logger';
const factory = process.env.TEST ? testing.createLoggerMock : createLogger;
export default factory({ [LogContexts.application]: 'foo' });
In a test you could:
import logger from './logger';
// in `fetch(url)` you'd use the logger like `logger.debug({url}, 'GET')` when the request is actually made
import fetch from './http';
test('it should cache request', () => {
logger.target.clear();
fetch('http://foo.bar/dummy.json');
expect(logger.target.messages.length).toBe(1);
fetch('http://foo.bar/dummy.json');
expect(logger.target.messages.length).toBe(1);
// you can also expect on the message:
expect(logger.target.messages.last.message).toBe('GET')
expect(logger.target.messages.last.context.url).toBe('http://foo.bar/dummy.json')
// or (mock target formater prefix the message with `[level:xxx] ` when there is a level)
expect(logger.target.lines.last).toBe('[level:20] GET')
// or filtering with level:
expect(logger.target.lines.debug.last).toBe('[level:20] GET')
});
Add to your project with npm
:
npm install --save bs-logger
or with yarn
:
yarn add bs-logger
You need to get a copy of the repository to run the tests:
git clone https://github.com/huafu/bs-logger.git
cd bs-logger
npm run test
Pull requests welcome!
We use SemVer for versioning. For the versions available, see the tags on this repository.
See also the list of contributors who participated in this project.
This project is licensed under the MIT License - see the LICENSE file for details
Hey dude! Help me out for a couple of :beers:!
0.2.6 (2018-11-10)
<a name="0.2.5"></a>
FAQs
Bare simple logger for NodeJS
The npm package bs-logger receives a total of 9,655,847 weekly downloads. As such, bs-logger popularity was classified as popular.
We found that bs-logger demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
Security News
Biden's executive order pushes for AI-driven cybersecurity, software supply chain transparency, and stronger protections for federal and open source systems.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.