Skip to content

Commit

Permalink
feat(logger): initial implementation
Browse files Browse the repository at this point in the history
this includes:
- ColdDeck class that handles creating new loggers with defaults and options
- Express Logger that attaches a logger dedicated to express
- test file to test out implementation until we write some real tests
  • Loading branch information
thatkookooguy committed Mar 11, 2019
1 parent 8c1beca commit 174b7f5
Show file tree
Hide file tree
Showing 5 changed files with 291 additions and 1 deletion.
15 changes: 14 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,26 @@
"@semantic-release/github": "^5.2.10",
"@semantic-release/npm": "^5.1.4",
"@semantic-release/release-notes-generator": "^7.1.4",
"@types/callsite": "^1.0.30",
"@types/lodash": "^4.14.122",
"all-contributors-cli": "^6.1.2",
"npm-check": "^5.9.0",
"semantic-release": "^16.0.0-beta.18",
"semantic-release-cli": "^4.1.0",
"semantic-release": "^16.0.0-beta.18"
"ts-node": "^8.0.3",
"typescript": "^3.3.3333"
},
"repository": {
"type": "git",
"url": "https://github.com/Kibibit/cold-deck.git"
},
"dependencies": {
"callsite": "^1.0.0",
"colors": "^1.3.3",
"express": "^4.16.4",
"lodash": "^4.17.11",
"mkdirp": "^0.5.1",
"moment": "^2.24.0",
"winston": "^3.2.1"
}
}
29 changes: 29 additions & 0 deletions src/cold-deck.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { coldDeck } from "./cold-deck";
import { logger } from './expressLogger';

const nice = coldDeck;

const console = nice.createBasic();

console.info('this is from the test file!');

const c = nice.child({ label: 'pizza' });

c.info('this is a child!', { service: 'tits', ass: 'is nice' });


/* jshint -W098 */
(function () {
const express = require('express'),
app = express();

app.set('port', (process.env.PORT || 5000));

app.use(logger()); //Log each request

var port = app.get("port");

app.listen(port, function () {
console.info('Server listening at port ' + port);
});
})();
136 changes: 136 additions & 0 deletions src/cold-deck.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import * as winston from 'winston';
import { isNil, map, isString, get } from 'lodash';
import colors from 'colors';
import { blue, bgBlue, bgGreen, green, yellow, red } from 'colors';
import moment from 'moment';
import path from 'path';
import { isObject } from 'util';

interface KbLogger extends winston.Logger {
table?: () => any;
}

interface ColdDeckOptions {
path: string;
createDefaultConsole: boolean;
}

const myCustomLevels = {
levels: {
error: 0,
warn: 1,
info: 2,
verbose: 3,
debug: 4,
silly: 5
},
colors: {
verbose: bgGreen,
silly: bgBlue,
info: blue,
debug: green,
warn: yellow,
error: red
}
};

const myFormat = winston.format.printf(({ level, message, scope, timestamp, tags }) => {
// console.log('the level is ', myCustomLevels.levels[ level ]);
const parsedTimestamp = moment(timestamp).format('YYYY-MM-DD [||] HH:mm:ss');
let parsedLabel = parseScope(scope);
parsedLabel = parsedLabel ? ` ${ parsedLabel }` : '';

// console.log('TAGS!', tags);

const parsedTags = map(tags, (tag) => colors[ tag.colors ](`[${ tag.msg }]`));

// console.log('parsed tags:');
// console.log(parsedTags);

return `${ green(parsedTimestamp) } ${ myCustomLevels.colors[ level ](level.toUpperCase()) }${ parsedLabel }${ parsedTags.length ? ' - ' + parsedTags.join('') : '' }: ${ message }`;
});

const defaultOptions: ColdDeckOptions = {
path: 'logs',
createDefaultConsole: true
};

export class ColdDeck {
// a user can create multiple consoles.
consoles = [];
mainConsole;
globalOptions: ColdDeckOptions;

constructor(options?: Partial<ColdDeckOptions>) {
options = isNil(options) ? {} : options;

options = Object.assign({}, defaultOptions, options);

this.globalOptions = options as ColdDeckOptions;
}

child(options: { [ key: string ]: any }) {
return this.createBasic(options);
}

createBasic(options?: { [ key: string ]: any }): KbLogger {
options = options || {};

const format = winston.format.combine(
// winston.format.colorize(),
winston.format.timestamp(),
winston.format.json()
);

const newLogger: winston.Logger = winston.createLogger({
level: 'info',
levels: myCustomLevels.levels,
format,
defaultMeta: { scope: 'global' },
transports: options.transports || [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
new winston.transports.File({ filename: path.join(this.globalOptions.path, '/error.log'), level: 'error' }),
new winston.transports.File({ filename: path.join(this.globalOptions.path, '/combined.log') })
]
});

// winston.addColors(myCustomLevels.colors);

if (process.env.NODE_ENV !== 'production') {
const consoleTransport = new winston.transports.Console({
format: myFormat
});

newLogger.add(consoleTransport);
}

this.mainConsole = this.mainConsole || newLogger;

// add a table option:
(newLogger as KbLogger).table = () => { };
const kbLogger: KbLogger = newLogger as KbLogger;



return kbLogger;
};
}

export const coldDeck = new ColdDeck();

function parseScope(scope: string | { msg: string; colors: string }) {
if (isString(scope)) {
return colors.bgWhite.magenta(`${ scope.toUpperCase() }`);
}

if (isObject(scope)) {
const scopeColors = get(colors, scope.colors) || colors.bgWhite.magenta;

return scopeColors(`${ scope.msg.toUpperCase() }`);
}

return '';
}
48 changes: 48 additions & 0 deletions src/expressLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import * as winston from 'winston';
import { coldDeck } from './cold-deck';
import path from 'path';

const kbConsole = coldDeck.child({
scope: 'Express',
label: 'Express',
transports: [
new winston.transports.File({ filename: path.join(coldDeck.globalOptions.path, '/express.log') })
]
});

export const logger = expressLogger;

function expressLogger(validate?) {

return function (req, res, next) {

if (!validate || validate(req, res)) {

kbConsole.info(req.url, {
scope: { msg: 'express', colors: 'bgYellow.magenta' },
tags: [
{ msg: req.ip === '::1' ? 'localhost' : req.ip, colors: 'red' },
{ msg: req.method, colors: 'green' },
{
msg: (/mobile/i.test(req.headers[ 'user-agent' ]) ? 'MOBILE' : 'DESKTOP'),
colors: 'grey'
}
]
});
// .time()
// .tag(
// { msg: 'Express', colors: 'cyan' },
// { msg: req.ip, colors: 'red' },
// { msg: req.method, colors: 'green' },
// {
// msg: (/mobile/i.test(req.headers[ 'user-agent' ]) ? 'MOBILE' : 'DESKTOP'),
// colors: 'grey'
// }
// )
// .info(req.url);
}

next();
};

};
64 changes: 64 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
{
"compilerOptions": {
/* Basic Options */
"target": "es5",
/* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs",
/* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true,
/* Enable all strict type-checking options. */
"noImplicitAny": false,
/* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}

0 comments on commit 174b7f5

Please sign in to comment.