Skip to content
This repository has been archived by the owner on Oct 25, 2023. It is now read-only.

Commit

Permalink
feat: add timestamps to log lines through _LOG_TIMESTAMP environment …
Browse files Browse the repository at this point in the history
…variable
  • Loading branch information
imurchie committed Jan 6, 2020
1 parent 1473b36 commit 3d2903a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/logging.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import npmlog from 'npmlog';
import _ from 'lodash';
import { unleakString } from './util';
import moment from 'moment';


// levels that are available from `npmlog`
const NPM_LEVELS = ['silly', 'verbose', 'debug', 'info', 'http', 'warn', 'error'];
const MAX_LOG_RECORDS_COUNT = 3000;

const PREFIX_TIMESTAMP_FORMAT = 'HH-mm-ss:SSS';

// mock log object used in testing mode
let mockLog = {};
for (let level of NPM_LEVELS) {
Expand Down Expand Up @@ -41,6 +44,14 @@ function _getLogger () {
return [logger, usingGlobalLog];
}

function getActualPrefix (prefix, logTimestamp = false) {
let actualPrefix = _.isFunction(prefix) ? prefix() : prefix;
if (logTimestamp) {
actualPrefix = `[${moment().format(PREFIX_TIMESTAMP_FORMAT)}] ${actualPrefix}`;
}
return actualPrefix;
}

function getLogger (prefix = null) {
let [logger, usingGlobalLog] = _getLogger();

Expand All @@ -55,10 +66,12 @@ function getLogger (prefix = null) {
configurable: true
});

const logTimestamp = parseInt(process.env._LOG_TIMESTAMP, 10) === 1;

// add all the levels from `npmlog`, and map to the underlying logger
for (const level of NPM_LEVELS) {
wrappedLogger[level] = function (...args) {
const actualPrefix = _.isFunction(prefix) ? prefix() : prefix;
const actualPrefix = getActualPrefix(prefix, logTimestamp);
for (const arg of args) {
const out = (_.isError(arg) && arg.stack) ? arg.stack : `${arg}`;
for (const line of out.split('\n')) {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"md5-file": "^4.0.0",
"mjpeg-server": "^0.3.0",
"mkdirp": "^0.5.1",
"moment": "^2.24.0",
"mv": "^2.1.1",
"ncp": "^2.0.0",
"npmlog": "^4.1.2",
Expand Down

0 comments on commit 3d2903a

Please sign in to comment.