Skip to content
This repository has been archived by the owner on Jul 8, 2024. It is now read-only.

Commit

Permalink
feat(logging): add timestamp to console logs
Browse files Browse the repository at this point in the history
  • Loading branch information
kv979w committed Aug 15, 2019
1 parent eaa1550 commit 7994a35
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 112 deletions.
188 changes: 95 additions & 93 deletions lib/log/logger.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
'use strict';
"use strict";

const { createLogger, format, transports } = require('winston');
import { createLogger, format, transports } from "winston";
import { getPackageManifest, getPackageName } from "../cli";
import path = require('path');
import fs = require('fs');
import _ = require('lodash');
import path = require("path");
import fs = require("fs");
import _ = require("lodash");

/*
* LSC's logging configuration module.
Expand All @@ -15,107 +15,109 @@ import _ = require('lodash');
* logger.error('an error');
* logger.warn('a warning');
*/
const FluentTransport = require('fluent-logger').support.winstonTransport();
const FluentTransport = require("fluent-logger").support.winstonTransport();

function mkdirSync(path: string): void {
try {
fs.mkdirSync(path);
} catch (error) {
if (error.code !== 'EEXIST') {
throw error;
}
try {
fs.mkdirSync(path);
} catch (error) {
if (error.code !== "EEXIST") {
throw error;
}
}
}
interface LoggerOptions {
fluentD?: {
host?: string
port?: number
timeout?: number
tag?: string
},
format?: {
timestamp?: boolean,
json?: boolean,
colorize?: boolean
},
cwd?: string
logDirectory?: string
fluentD?: {
host?: string;
port?: number;
timeout?: number;
tag?: string;
};
format?: {
json?: boolean;
colorize?: boolean;
};
cwd?: string;
logDirectory?: string;
}
// default format for Console, error at winston: if not json is specified is not logging in console
const loggerFormat = format.printf(({level, message }) => {
return `${level}: ${message}`;
const loggerFormat = format.printf(({ timestamp, level, message }) => {
return `${timestamp} ${level}: ${message}`;
});
export const Logger = (options: LoggerOptions) => {
options = _.defaultsDeep(options || {}, {
fluentD: {},
logDirectory: null,
format: {
json: false,
colorize: false
},
cwd: process.cwd()
});

options = _.defaultsDeep(options || {}, {
fluentD: {},
logDirectory: null,
format: {
timestamp: true,
json: false,
colorize: false
},
cwd: process.cwd()
});

// Defining custom formats
const styleFormats = [];
// Defining custom formats
const styleFormats = [
format.timestamp({
format: "YYYY-MM-DD HH:mm:ss"
})
];

// special case: if json is not defined , use by default the custom format
if (options.format.json === false) {
// going to global
styleFormats.push( loggerFormat);
}
else{
styleFormats.push(format.json());
// special case: if json is not defined , use by default the custom format
// Example: https://github.com/winstonjs/winston/blob/master/examples/custom-timestamp.js
if (!options.format.json) {
styleFormats.push(loggerFormat);
} else {
styleFormats.push(format.json());
}
// TODO: enable dynamic formats and parameters , for now it is only using basic types with no parameters
for (const key of Object.keys(options.format)) {
if (options.format[key]) {
styleFormats.push(format[key]());
}
// TODO: enable dynamic formats and parameters , for now it is only using basic types with no parameters
_.forEach(['colorize', 'timestamp'], (value) => {
if (_.get(options.format, `${value}`) === true) {
styleFormats.push(format[`${value}`]());
}
});
const _logger = createLogger({
format: format.combine(...styleFormats)
});
// Adding a new Console transport
_logger.add(new transports.Console());
if (options.logDirectory) {
// Create the log directory if it doesn't exist
mkdirSync(options.logDirectory);
}
const logger = createLogger({
format: format.combine(...styleFormats)
});

_logger.add(new transports.File({
filename: path.resolve(options.logDirectory, 'app.log'),
maxFiles: 5,
maxsize: 10485760,
level: 'info'
}));
}
// Adding fluentD transport
if (!_.isEmpty(options.fluentD)) {
let name: string = getPackageName(getPackageManifest(options.cwd));
// Adding a new Console transport
logger.add(new transports.Console());
if (options.logDirectory) {
// Create the log directory if it doesn't exist
mkdirSync(options.logDirectory);

options = _.defaultsDeep(options, {
fluentD: {
host: 'localhost',
port: 24224,
timeout: 3.0,
tag: name || 'labshare'
}
});
logger.add(
new transports.File({
filename: path.resolve(options.logDirectory, "app.log"),
maxFiles: 5,
maxsize: 10485760,
level: "info"
})
);
}
// Adding fluentD transport
if (!_.isEmpty(options.fluentD)) {
let name: string = getPackageName(getPackageManifest(options.cwd));

_logger.add(new FluentTransport(options.fluentD.tag, options.fluentD));
}
// Workaround to support the Morgan request logging middleware
return _.assign(_logger, {
stream: () => {
let self: any = this;
return {
write(options?: any): void {
self.info(options);
}
}
}
});;
options = _.defaultsDeep(options, {
fluentD: {
host: "localhost",
port: 24224,
timeout: 3.0,
tag: name || "labshare"
}
});

}
logger.add(new FluentTransport(options.fluentD.tag, options.fluentD));
}
// Workaround to support the Morgan request logging middleware
return _.assign(logger, {
stream: () => {
let self: any = this;
return {
write(options?: any): void {
self.info(options);
}
};
}
});
};
34 changes: 15 additions & 19 deletions test/lib/unit/cli/start_spec.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
import {checkVersion} from "../../../../lib/check-self-update";
import {start} from "../../../../lib/cli";
import { checkVersion } from "../../../../lib/check-self-update";
import { start } from "../../../../lib/cli";

describe('.start()', () => {
describe(".start()", () => {
afterEach(() => {
delete global.LabShare;
});

afterEach(() => {
delete global.LabShare;
});

it('bootstraps the CLI', () => {
expect(global.LabShare).toBeUndefined();

start({});
it("bootstraps the CLI", () => {
expect(global.LabShare).toBeUndefined();

expect(global.LabShare).toBeDefined();
});

describe('.checkVersion()', () => {
start({});

it('checks if the installed version of "package-name" needs to be updated', async () => {
await checkVersion({name: 'lsc', logger: console.log});
});
expect(global.LabShare).toBeDefined();
});

describe(".checkVersion()", () => {
it('checks if the installed version of "package-name" needs to be updated', async () => {
await checkVersion({ name: "lsc", logger: console.log });
});

});
});

0 comments on commit 7994a35

Please sign in to comment.