diff options
| -rw-r--r-- | .gitignore | 3 | ||||
| -rw-r--r-- | package.json | 5 | ||||
| -rw-r--r-- | src/FileRouter.ts | 2 | ||||
| -rw-r--r-- | src/db/orm.ts | 15 | ||||
| -rw-r--r-- | src/files.ts | 13 | ||||
| -rw-r--r-- | src/index.ts | 44 | ||||
| -rw-r--r-- | src/logger.ts | 248 | ||||
| -rw-r--r-- | yarn.lock | 99 |
8 files changed, 384 insertions, 45 deletions
@@ -16,5 +16,8 @@ POSTGRES_logfile # Vim swap files *.sw* +# log output +logs/ + # Typedoc-generated documentation docs/ diff --git a/package.json b/package.json index 8359cf3..ecc5756 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ }, "dependencies": { "@types/body-parser": "0.0.33", + "@types/colors": "^1.1.3", "@types/express": "^4.0.33", "@types/express-jwt": "^0.0.38", "@types/jsonwebtoken": "^7.2.5", @@ -46,7 +47,9 @@ "@types/passport-local": "^1.0.32", "@types/sequelize": "^4.27.5", "@types/uuid": "^3.4.3", + "@types/winston": "^2.3.8", "body-parser": "^1.18.2", + "colors": "^1.1.2", "express": "^4.16.2", "express-jwt": "^5.3.0", "jsonwebtoken": "^8.1.1", @@ -56,12 +59,14 @@ "passport-local": "^1.0.0", "pg": "^7.4.1", "pg-hstore": "^2.3.2", + "pg-native": "^2.2.0", "reflect-metadata": "^0.1.12", "sequelize": "^4.32.7", "sequelize-typescript": "^0.6.2", "ts-node": "^3.3.0", "typescript": "^2.7.1", "uuid": "^3.2.1", + "winston": "^2.4.0", "xlsx": "^0.11.19" } } diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 8d13401..1cef85d 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -70,7 +70,7 @@ const postLog: Middleware = return; } for (const item of req.body) { - logger.log(item.level, item.value, { + logger.forward(item.level, item.value, { component: item.component, user: req.user.username, external: true diff --git a/src/db/orm.ts b/src/db/orm.ts index 01d8037..fd70fbb 100644 --- a/src/db/orm.ts +++ b/src/db/orm.ts @@ -1,12 +1,15 @@ +import { logQuery } from '../logger'; import { Sequelize } from 'sequelize-typescript'; const seq: Sequelize = new Sequelize({ - database: 'be4', - dialect: 'postgres', - username: 'admin', - password: '', - operatorsAliases: false, - modelPaths: [`${__dirname}/model`] + database: 'be4', + dialect: 'postgres', + username: 'admin', + password: '', + operatorsAliases: false, + modelPaths: [`${__dirname}/model`], + logging: logQuery, + benchmark: true }); export default seq; diff --git a/src/files.ts b/src/files.ts index daab817..fb22013 100644 --- a/src/files.ts +++ b/src/files.ts @@ -1,6 +1,7 @@ import * as fs from 'fs'; const CONTENT_BASE_DIRECTORY: string = './files'; +const LOG_BASE_DIRECTORY: string = './logs'; const path: (filename: string, projectName: string) => string = (filename: string, projectName: string): string => { @@ -13,10 +14,20 @@ const writableStream: return fs.createWriteStream(path(filename, projectName)); }; +const logPath: + (type: string, projectName?: string) => string = + (type: string, projectName?: string): string => { + return projectName + ? `${LOG_BASE_DIRECTORY}/projects/${projectName}/${type}` + : `${LOG_BASE_DIRECTORY}/general/${type}`; +}; + export const files: { path: (f: string, p: string) => string; writableStream: (f: string, p: string) => fs.WriteStream; + logPath: (t: string, p?: string) => string; } = { path, - writableStream + writableStream, + logPath }; diff --git a/src/index.ts b/src/index.ts index c6adf32..601f510 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,10 +1,12 @@ -/* tslint:disable:no-console - * This only goes here until we have a logging system */ +import { logger } from './logger'; -console.log('begin import'); +logger.info('Starting up server'); + +logger.info('Importing server logic'); import { default as app } from './app'; + +logger.info('Importing database ORM'); import { default as seq } from './db/orm'; -console.log('end import'); import { default as User } from './db/model/User'; import { default as UserGroup } from './db/model/UserGroup'; @@ -15,19 +17,27 @@ const DEFAULT_PORT: number = 3000; const port: number = process.env.PORT ? process.env.PORT : DEFAULT_PORT; +logger.info(`Port ${port} chosen`); // tslint:disable:no-floating-promises (async(): Promise<void> => { - console.log('Booting PSQL database'); + try { + logger.info('Authenticating with database'); + await seq.authenticate(); + } catch (err) { + return logger.error(`Cannot authenticate with database: ${err}`); + } - await seq.authenticate(); - - console.log('Resetting Database'); - - await seq.sync({ - force: true - }); + try { + logger.info('Resetting Database'); + await seq.sync({ + force: true + }); + } catch (err) { + return logger.error(`Cannot synchronise with database: ${err}`); + } + logger.info('Adding admin privileges'); const admin: UserGroup = new UserGroup({ name: 'admin', canCreateUsers: true, @@ -42,8 +52,7 @@ const port: number = process.env.PORT await admin.save(); - console.log(admin.id); - + logger.info('Adding admin user'); const root: User = new User({ username: 'hafeez', password: 'pass', @@ -52,13 +61,12 @@ const port: number = process.env.PORT root.save(); - console.log('Booting ExpressJS server'); - + logger.info('Booting ExpressJS server'); app.listen(port, (err: Error) => { if (err) { - return console.log(err); + return logger.error(`Error on ExpressJS startup: ${err}`); } else { - return console.log(`server is listening on port ${port}`); + return logger.info(`Server started on port ${port}`); } }); })(); diff --git a/src/logger.ts b/src/logger.ts index 70c6455..953a341 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -1,26 +1,240 @@ /* tslint:disable:no-any */ -interface Metadata { +import * as colors from 'colors/safe'; +import * as winston from 'winston'; + +import { files } from './files'; + +type LogLevel = 'critical' | 'error' | 'warning' | 'security' | 'info'; + +const LOG_LEVELS: winston.LoggerOptions = { + info: 4, + security: 3, + warning: 2, + error: 1, + critical: 0 +}; + +const LOG_LEVEL_COLOURS: { + [key: string]: (s: string) => string; +} = { + info: colors.cyan, + security: colors.blue, + warning: colors.yellow, + error: colors.red, + critical: colors.red +}; + +interface LoggingMetadata { + component?: string; + user?: string; [key: string]: any; } +const consoleTransport: winston.TransportInstance = + new winston.transports.Console({ + name: 'consoleTransport', + level: 'info', + silent: false, + handleExceptions: true, + humanReadableUncaughtException: true, + formatter: ( + { level, message }: + { level: string; message: string } + ): string => { + let out: string = ''; + const stamp: string = new Date().toLocaleTimeString(); + out += `[${LOG_LEVEL_COLOURS[level](`${stamp} ${level}`)}] `; + out += (level === 'critical') + ? colors.red(message) + : message; + return out; + }, + stderrLevels: [ 'error', 'critical' ] +}); + +const basicFileTransport: winston.TransportInstance = + new winston.transports.File({ + name: 'basicFileTransport', + level: 'info', + label: 'Basic File Transport', + silent: false, + colorize: false, + timestamp: true, + filename: files.logPath('basic'), + maxSize: 1000000, + maxFiles: 100, + stream: undefined, + json: true, + eol: '\n', + prettyPrint: false, + depth: null, + logstash: false, + showLevel: true, + formatter: undefined, + tailable: true, + maxRetries: 2, + zippedArchive: true, + options: { + flags: 'a' + } +}); + +const criticalFileTransport: winston.TransportInstance = + new winston.transports.File({ + name: 'criticalFileTransport', + level: 'critical', + label: 'Critical Reporter', + silent: false, + colorize: false, + timestamp: true, + filename: files.logPath('critical'), + maxSize: 1000000, + maxFiles: 10, + stream: undefined, + json: true, + eol: '\n', + prettyPrint: false, + depth: null, + handleExceptions: true, + logstash: false, + showLevel: true, + formatter: undefined, + tailable: true, + maxRetries: 2, + zippedArchive: true, + options: { + flags: 'a' + } +}); + +const queryFileTransport: winston.TransportInstance = + new winston.transports.File({ + name: 'queryFileTransport', + level: 'info', + label: 'Query Logs', + silent: false, + colorize: false, + timestamp: true, + filename: files.logPath('queries'), + maxSize: 1000000, + maxFiles: 100, + stream: undefined, + json: true, + eol: '\n', + prettyPrint: false, + depth: null, + handleExceptions: false, + logstash: false, + showLevel: false, + formatter: undefined, + tailable: true, + maxRetries: 2, + zippedArchive: true, + options: { + flags: 'a' + } +}); + +const basicLogger: winston.LoggerInstance = new winston.Logger({ + transports: [ + consoleTransport, + basicFileTransport, + criticalFileTransport + ], + levels: LOG_LEVELS +}); + +const queryLogger: winston.LoggerInstance = new winston.Logger({ + transports: [ + queryFileTransport + ], + levels: { + info: 0 + } +}); + +type LogFunction = (message: string, meta?: LoggingMetadata) => void; + +const makeLogFunction: (level: LogLevel) => LogFunction = ( + level: LogLevel +): LogFunction => { + return ( + message: string, meta: LoggingMetadata = {} + ): void => { + meta.user = meta.user || '_BE4_system'; + meta.component = meta.component || 'core'; + basicLogger.log(level, message, meta); + }; +}; + +interface FetchParams { + before?: Date; + after?: Date; +} + +interface LogItem { + component: string; + level: LogLevel; + value: string; + username: string; + timestamp: string; +} + +const fetchLogs: (level: LogLevel, params?: FetchParams) => LogItem[] = ( + level: LogLevel, params: FetchParams = {} +): LogItem[] => { + const matches: (log: any, level: LogLevel, params?: FetchParams) => boolean = ( + log: any, minLevel: LogLevel, fetchParams: FetchParams = {} + ): boolean => { + const time: Date = new Date(log.timestamp); + if (params.before && params.before < time) { + return false; + } else if (params.after && params.after > time) { + return false; + } else { + return true; + } + }; + const out: LogItem[] = []; + basicLogger.stream({ level }).on('log', (log: any): void => { + if (matches(log, level, params)) { + out.push({ + component: log.meta.component, + level: log.level, + value: log.message, + username: log.user, + timestamp: log.timestamp + }); + } + }); + return out; +}; + export const logger: { - log: ( - level: string, - value: any, - meta: Metadata - ) => void; - fetch: ( - level: string, - meta: Metadata - ) => any[]; + info: LogFunction; + security: LogFunction; + warning: LogFunction; + error: LogFunction; + critical: LogFunction; isEnabled: () => boolean; + forward: (level: LogLevel, message: string, meta: LoggingMetadata) => void; + fetch: (level: LogLevel, params?: FetchParams) => LogItem[]; } = { - log: (level: string, value: any, meta: Metadata): void => { - return; - }, - fetch: (level: string, meta: Metadata): any[] => { - return []; - }, - isEnabled: (): boolean => false + info: makeLogFunction('info'), + security: makeLogFunction('security'), + warning: makeLogFunction('warning'), + error: makeLogFunction('error'), + critical: makeLogFunction('critical'), + isEnabled: (): boolean => !basicFileTransport.silent, + forward: basicLogger.log, + fetch: fetchLogs +}; + +export const logQuery: (query: string, duration: string) => void = ( + query: string, duration: string +): void => { + queryLogger.info(query, { + duration + }); }; @@ -38,6 +38,10 @@ version "3.5.2" resolved "https://registry.yarnpkg.com/@types/chai/-/chai-3.5.2.tgz#c11cd2817d3a401b7ba0f5a420f35c56139b1c1e" +"@types/colors@^1.1.3": + version "1.1.3" + resolved "https://registry.yarnpkg.com/@types/colors/-/colors-1.1.3.tgz#5413b0a7a1b16dd18be0e3fd57d2feecc81cc776" + "@types/continuation-local-storage@*": version "3.2.1" resolved "https://registry.yarnpkg.com/@types/continuation-local-storage/-/continuation-local-storage-3.2.1.tgz#a33e0df9dce9b424d1c98fc4fdebd8578dceec7e" @@ -227,6 +231,12 @@ version "6.3.0" resolved "https://registry.yarnpkg.com/@types/validator/-/validator-6.3.0.tgz#d7454bd67c6a933a9dbe939ae16edbf0f6894e70" +"@types/winston@^2.3.8": + version "2.3.8" + resolved "https://registry.yarnpkg.com/@types/winston/-/winston-2.3.8.tgz#88964f45ecb5ed1feb4bfb38a24316bee8bf8768" + dependencies: + "@types/node" "*" + abbrev@1: version "1.1.1" resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" @@ -364,6 +374,10 @@ async@^1.4.0, async@^1.5.0, async@^1.5.2: version "1.5.2" resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" +async@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/async/-/async-1.0.0.tgz#f8fc04ca3a13784ade9e1641af98578cfbd647a9" + asynckit@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" @@ -424,6 +438,10 @@ binary-extensions@^1.0.0: version "1.11.0" resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.11.0.tgz#46aa1751fb6a2f93ee5e689bb1087d4b14c6c205" +bindings@1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.2.1.tgz#14ad6113812d2d37d72e67b4cacb4bb726505f11" + block-stream@*: version "0.0.9" resolved "https://registry.yarnpkg.com/block-stream/-/block-stream-0.0.9.tgz#13ebfe778a03205cfe03751481ebb4b3300c126a" @@ -669,6 +687,14 @@ color-name@^1.1.1: version "1.1.3" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" +colors@1.0.x: + version "1.0.3" + resolved "https://registry.yarnpkg.com/colors/-/colors-1.0.3.tgz#0433f44d809680fdeb60ed260f1b0c262e82a40b" + +colors@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/colors/-/colors-1.1.2.tgz#168a4701756b6a7f51a12ce0c97bfa28c084ed63" + combined-stream@^1.0.5, combined-stream@~1.0.5: version "1.0.6" resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.6.tgz#723e7df6e801ac5613113a7e445a9b69cb632818" @@ -779,6 +805,10 @@ crypto-random-string@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/crypto-random-string/-/crypto-random-string-1.0.0.tgz#a230f64f568310e1498009940790ec99545bca7e" +cycle@1.0.x: + version "1.0.3" + resolved "https://registry.yarnpkg.com/cycle/-/cycle-1.0.3.tgz#21e80b2be8580f98b468f379430662b046c34ad2" + dashdash@^1.12.0: version "1.14.1" resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0" @@ -1054,6 +1084,10 @@ extsprintf@^1.2.0: version "1.4.0" resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f" +eyes@0.1.x: + version "0.1.8" + resolved "https://registry.yarnpkg.com/eyes/-/eyes-0.1.8.tgz#62cf120234c683785d902348a800ef3e0cc20bc0" + fill-range@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-4.0.0.tgz#d544811d428f98eb06a63dc402d2403c328c38f7" @@ -1394,7 +1428,7 @@ inflight@^1.0.4: once "^1.3.0" wrappy "1" -inherits@2, inherits@2.0.3, inherits@^2.0.1, inherits@~2.0.0, inherits@~2.0.3: +inherits@2, inherits@2.0.3, inherits@^2.0.1, inherits@~2.0.0, inherits@~2.0.1, inherits@~2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" @@ -1565,6 +1599,10 @@ is-typedarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" +isarray@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf" + isarray@1.0.0, isarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" @@ -1587,7 +1625,7 @@ isobject@^3.0.0, isobject@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" -isstream@~0.1.2: +isstream@0.1.x, isstream@~0.1.2: version "0.1.2" resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" @@ -1734,6 +1772,13 @@ lazy-cache@^2.0.2: dependencies: set-getter "^0.1.0" +libpq@^1.7.0: + version "1.8.7" + resolved "https://registry.yarnpkg.com/libpq/-/libpq-1.8.7.tgz#c2deb121e28f7f84bd3b2451afff68b6663e74f9" + dependencies: + bindings "1.2.1" + nan "^2.3.0" + lodash._baseassign@^3.0.0: version "3.2.0" resolved "https://registry.yarnpkg.com/lodash._baseassign/-/lodash._baseassign-3.2.0.tgz#8c38a099500f215ad09e59f1722fd0c52bfe0a4e" @@ -2246,10 +2291,32 @@ pg-hstore@^2.3.2: dependencies: underscore "^1.7.0" +pg-int8@1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/pg-int8/-/pg-int8-1.0.1.tgz#943bd463bf5b71b4170115f80f8efc9a0c0eb78c" + +pg-native@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/pg-native/-/pg-native-2.2.0.tgz#bc84756f4ecbf600ff7cb48ea5854141830cf1e4" + dependencies: + libpq "^1.7.0" + pg-types "^1.12.1" + readable-stream "1.0.31" + pg-pool@~2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/pg-pool/-/pg-pool-2.0.3.tgz#c022032c8949f312a4f91fb6409ce04076be3257" +pg-types@^1.12.1: + version "1.13.0" + resolved "https://registry.yarnpkg.com/pg-types/-/pg-types-1.13.0.tgz#75f490b8a8abf75f1386ef5ec4455ecf6b345c63" + dependencies: + pg-int8 "1.0.1" + postgres-array "~1.0.0" + postgres-bytea "~1.0.0" + postgres-date "~1.0.0" + postgres-interval "^1.1.0" + pg-types@~1.12.1: version "1.12.1" resolved "https://registry.yarnpkg.com/pg-types/-/pg-types-1.12.1.tgz#d64087e3903b58ffaad279e7595c52208a14c3d2" @@ -2377,6 +2444,15 @@ rc@^1.0.1, rc@^1.1.6, rc@^1.1.7: minimist "^1.2.0" strip-json-comments "~2.0.1" +readable-stream@1.0.31: + version "1.0.31" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.0.31.tgz#8f2502e0bc9e3b0da1b94520aabb4e2603ecafae" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.1" + isarray "0.0.1" + string_decoder "~0.10.x" + readable-stream@^2.0.2, readable-stream@^2.0.5, readable-stream@^2.0.6, readable-stream@^2.1.4: version "2.3.4" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.4.tgz#c946c3f47fa7d8eabc0b6150f4a12f69a4574071" @@ -2748,6 +2824,10 @@ sshpk@^1.7.0: jsbn "~0.1.0" tweetnacl "~0.14.0" +stack-trace@0.0.x: + version "0.0.10" + resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz#547c70b347e8d32b4e108ea1a2a159e5fdde19c0" + static-extend@^0.1.1: version "0.1.2" resolved "https://registry.yarnpkg.com/static-extend/-/static-extend-0.1.2.tgz#60809c39cbff55337226fd5e0b520f341f1fb5c6" @@ -2784,6 +2864,10 @@ string-width@^2.0.0, string-width@^2.1.1: is-fullwidth-code-point "^2.0.0" strip-ansi "^4.0.0" +string_decoder@~0.10.x: + version "0.10.31" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.10.31.tgz#62e203bc41766c6c28c9fc84301dab1c5310fa94" + string_decoder@~1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.0.3.tgz#0fc67d7c141825de94282dd536bec6b9bce860ab" @@ -3207,6 +3291,17 @@ window-size@0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d" +winston@^2.4.0: + version "2.4.0" + resolved "https://registry.yarnpkg.com/winston/-/winston-2.4.0.tgz#808050b93d52661ed9fb6c26b3f0c826708b0aee" + dependencies: + async "~1.0.0" + colors "1.0.x" + cycle "1.0.x" + eyes "0.1.x" + isstream "0.1.x" + stack-trace "0.0.x" + wkx@^0.4.1: version "0.4.2" resolved "https://registry.yarnpkg.com/wkx/-/wkx-0.4.2.tgz#776d35a634a5c22e656e4744bdeb54f83fd2ce8d" |
