Skip to content

Commit

Permalink
Merge pull request #98 from CMSgov/logging-upgrade
Browse files Browse the repository at this point in the history
Add logger support
  • Loading branch information
shaselton-usds authored Aug 18, 2023
2 parents c77672b + 24e2fc1 commit c919af9
Show file tree
Hide file tree
Showing 8 changed files with 1,475 additions and 92 deletions.
1,401 changes: 1,369 additions & 32 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,12 @@
},
"dependencies": {
"axios": "^1.2.1",
"chalk": "^3.0.0",
"commander": "^8.3.0",
"fs-extra": "^10.0.0",
"readline-sync": "^1.4.10",
"temp": "^0.9.4",
"winston": "^3.10.0",
"yauzl": "^2.10.0"
}
}
19 changes: 9 additions & 10 deletions src/DockerManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@ import path from 'path';
import { exec } from 'child_process';
import fs from 'fs-extra';
import temp from 'temp';
import { logger } from './logger';

export class DockerManager {
containerId = '';

constructor(public debug = false) {}
constructor() {}

private async initContainerId(): Promise<void> {
this.containerId = await util
.promisify(exec)('docker images validator:latest --format "{{.ID}}"')
.then(result => result.stdout.trim())
.catch(reason => {
console.log(reason.stderr);
logger.error(reason.stderr);
return '';
});
}
Expand All @@ -37,10 +38,8 @@ export class DockerManager {
const containerLocationPath = path.join(outputDir, 'locations.json');
// copy output files after it finishes
const runCommand = this.buildRunCommand(schemaPath, dataPath, outputDir, schemaName);
console.log('Running validator container...');
if (this.debug) {
console.log(runCommand);
}
logger.info('Running validator container...');
logger.debug(runCommand);
return util
.promisify(exec)(runCommand)
.then(result => {
Expand All @@ -53,7 +52,7 @@ export class DockerManager {
fs.copySync(containerOutputPath, outputPath);
} else {
const outputText = fs.readFileSync(containerOutputPath, 'utf-8');
console.log(outputText);
logger.info(outputText);
}
}
if (fs.existsSync(containerLocationPath)) {
Expand All @@ -74,19 +73,19 @@ export class DockerManager {
fs.copySync(containerOutputPath, outputPath);
} else {
const outputText = fs.readFileSync(containerOutputPath, 'utf-8');
console.log(outputText);
logger.info(outputText);
}
}
process.exitCode = 1;
return { pass: false };
});
} else {
console.log('Could not find a validator docker container.');
logger.error('Could not find a validator docker container.');
process.exitCode = 1;
return { pass: false };
}
} catch (error) {
console.log(`Error when running validator container: ${error}`);
logger.error(`Error when running validator container: ${error}`);
process.exitCode = 1;
return { pass: false };
}
Expand Down
3 changes: 2 additions & 1 deletion src/SchemaManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { exec } from 'child_process';
import util from 'util';
import { config } from './utils';
import temp from 'temp';
import { logger } from './logger';

export class SchemaManager {
private version: string;
Expand Down Expand Up @@ -41,7 +42,7 @@ export class SchemaManager {
return true;
} else {
// we didn't find your tag. maybe you mistyped it, so show the available ones.
console.log(
logger.error(
`Could not find a schema version named "${version}". Available versions are:\n${tags.join(
'\n'
)}`
Expand Down
19 changes: 10 additions & 9 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@ import {
import temp from 'temp';
import { SchemaManager } from './SchemaManager';
import { DockerManager } from './DockerManager';
import { logger } from './logger';

export async function validate(dataFile: string, schemaVersion: string, options: OptionValues) {
// check to see if supplied json file exists
if (!fs.existsSync(dataFile)) {
console.log(`Could not find data file: ${dataFile}`);
logger.error(`Could not find data file: ${dataFile}`);
process.exitCode = 1;
return;
}
Expand All @@ -38,7 +39,7 @@ export async function validate(dataFile: string, schemaVersion: string, options:
.then(async schemaPath => {
temp.track();
if (schemaPath != null) {
const dockerManager = new DockerManager(options.debug);
const dockerManager = new DockerManager();
const containerResult = await dockerManager.runContainer(
schemaPath,
options.target,
Expand Down Expand Up @@ -72,7 +73,7 @@ export async function validate(dataFile: string, schemaVersion: string, options:
}
}
} else {
console.log('No schema available - not validating.');
logger.error('No schema available - not validating.');
process.exitCode = 1;
}
temp.cleanupSync();
Expand All @@ -98,7 +99,7 @@ export async function validateFromUrl(
})
.then(async schemaPath => {
if (schemaPath != null) {
const dockerManager = new DockerManager(options.debug);
const dockerManager = new DockerManager();
const dataFile = await downloadDataFile(dataUrl, temp.mkdirSync());
if (typeof dataFile === 'string') {
const containerResult = await dockerManager.runContainer(
Expand Down Expand Up @@ -153,12 +154,12 @@ export async function validateFromUrl(
dataFile.zipFile.close();
}
} else {
console.log('No schema available - not validating.');
logger.error('No schema available - not validating.');
process.exitCode = 1;
}
});
} else {
console.log('Exiting.');
logger.info('Exiting.');
process.exitCode = 1;
}
}
Expand All @@ -170,15 +171,15 @@ export async function update() {
await util.promisify(exec)(
`git clone ${config.SCHEMA_REPO_URL} "${config.SCHEMA_REPO_FOLDER}"`
);
console.log('Retrieved schemas.');
logger.info('Retrieved schemas.');
} else {
await util.promisify(exec)(
`git -C "${config.SCHEMA_REPO_FOLDER}" checkout master && git -C "${config.SCHEMA_REPO_FOLDER}" pull --no-rebase -t`
);
console.log('Updated schemas.');
logger.info('Updated schemas.');
}
} catch (error) {
console.log(`Error when updating available schemas: ${error}`);
logger.error(`Error when updating available schemas: ${error}`);
process.exitCode = 1;
}
}
7 changes: 4 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import { program, Option } from 'commander';
import { validate, update, validateFromUrl } from './commands';
import { config } from './utils';
import { logger } from './logger';

main().catch(error => {
console.log(`Encountered an unexpected error: ${error}`);
logger.error(`Encountered an unexpected error: ${error}`);
});

async function main() {
Expand All @@ -15,8 +16,8 @@ async function main() {
.option('-d, --debug', 'show debug output')
.hook('preAction', (thisCommand, actionCommand) => {
if (thisCommand.opts().debug) {
console.log(process.argv.join(' '));
actionCommand.setOptionValue('debug', true);
logger.level = 'debug';
logger.debug(process.argv.join(' '));
}
})
.command('validate')
Expand Down
39 changes: 39 additions & 0 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { createLogger, format, transports, Logger, LeveledLogMethod } from 'winston';
import chalk from 'chalk';

const { printf } = format;

const customLevels = {
error: 0,
warn: 1,
menu: 2,
info: 2,
debug: 3
};

const printer = printf(info => {
let level: string;
switch (info.level) {
case 'debug':
level = chalk.whiteBright.bgBlue(`${info.level}`);
break;
case 'info':
level = chalk.whiteBright.bgGreen(`${info.level} `);
break;
case 'warn':
level = chalk.whiteBright.bgRgb(195, 105, 0)(`${info.level} `);
break;
case 'error':
level = chalk.whiteBright.bgRed(`${info.level}`);
break;
default:
break;
}
return `${level} ${info.message}`;
});

export const logger = createLogger({
levels: customLevels,
format: printer,
transports: [new transports.Console()]
}) as Logger & Record<keyof typeof customLevels, LeveledLogMethod>;
Loading

0 comments on commit c919af9

Please sign in to comment.