From 31d18c41085b3ee3774083704182f14c8c0fd4b8 Mon Sep 17 00:00:00 2001 From: Justyna Janczyszyn <4153982+jjanczyszyn@users.noreply.github.com> Date: Thu, 22 Nov 2018 17:56:43 +0100 Subject: [PATCH] added support for global prefix --- README.md | 12 ++++++++++++ index.js | 4 ++++ test/fastlog.test.js | 11 ++++++++++- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0a0afff..782263b 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,18 @@ logger.error('This town ain\'t big enough for the two of us!'); // error [configured] This town ain't big enough for the two of us! ``` +It's also possible to set a global prefix: +- Configure global prefix by specifying a `FASTLOG_GLOBAL_PREFIX` environment variable. +```javascript +process.env.FASTLOG_GLOBAL_PREFIX = '[ipAddress]'; +``` + +```javascript +var logger = require('fastlog')('configured', 'error', '${level} [${ category }] <${timestamp}>'); +logger.error('You\'ve got a friend in me.'); +// [ipAddress] error [configured] You've got a friend in me. +``` + ## Usage via shell scripts You may also use fastlog in shell scripts. First, make sure fastlog is installed globally diff --git a/index.js b/index.js index 99f1a8e..9d6f27d 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,10 @@ var util = require('util'); module.exports = function(category, level, template) { category = category || 'default'; template = template || '[${timestamp}] [${level}] [${category}]'; + if (process.env.FASTLOG_GLOBAL_PREFIX) { + template = process.env.FASTLOG_GLOBAL_PREFIX + ' ' + template; + } + var levels = ['debug', 'info', 'warn', 'error', 'fatal']; return _(levels).reduce(function(logger, l) { logger[l] = function() { diff --git a/test/fastlog.test.js b/test/fastlog.test.js index 30f66d7..3ae7179 100644 --- a/test/fastlog.test.js +++ b/test/fastlog.test.js @@ -2,7 +2,6 @@ var assert = require('assert'); var sinon = require('sinon'); var fastlog = require('../index.js'); -var util = require('util'); var spy = sinon.spy(console, 'log'); describe('string logging', function() { @@ -87,4 +86,14 @@ describe('string logging', function() { assert.ok(spy.calledWith('%s %s', sinon.match(/\[error\] \{configured\} -- .+?:/), 'to infinity and beyond!')); assert.equal(spy.callCount, 1); }); + + it('should include FASTLOG_GLOBAL_PREFIX in prefix', function() { + process.env.FASTLOG_GLOBAL_PREFIX = '[global prefix]'; + var log = fastlog(); + log.error('reach for the sky!'); + assert.ok( + spy.calledWith('%s %s', sinon.match(/\[global prefix\] \[.+\] \[error\] \[default\]/), 'reach for the sky!') + ); + delete process.env.FASTLOG_GLOBAL_PREFIX; + }); });