Skip to content

Commit

Permalink
Add ability to set log level and move http logs to level http
Browse files Browse the repository at this point in the history
  • Loading branch information
butlerx committed Jan 31, 2022
1 parent 6e7817e commit 0b5262b
Show file tree
Hide file tree
Showing 10 changed files with 73 additions and 16 deletions.
15 changes: 10 additions & 5 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*/
import yargs from 'yargs';
import { createRequire } from 'module';
import { logger } from './shared/logger.js';
import { setLevel, logger } from './shared/logger.js';
import { start } from './server.js';
import { loadConfigFile, mergeCliConf } from './shared/config.js';

Expand Down Expand Up @@ -104,6 +104,10 @@ const opts = yargs
'Allow WeTTY to use the `host` param in a url as ssh destination',
type: 'boolean',
})
.option('log-level', {
description: 'set log level of wetty server',
type: 'string',
})
.option('help', {
alias: 'h',
type: 'boolean',
Expand All @@ -114,11 +118,12 @@ const opts = yargs
if (!opts.help) {
loadConfigFile(opts.conf)
.then(config => mergeCliConf(opts, config))
.then(conf =>
start(conf.ssh, conf.server, conf.command, conf.forceSSH, conf.ssl),
)
.then(conf => {
setLevel(conf.logLevel);
start(conf.ssh, conf.server, conf.command, conf.forceSSH, conf.ssl);
})
.catch((err: Error) => {
logger.error(err);
logger().error('error in server', { err });
process.exitCode = 1;
});
} else {
Expand Down
3 changes: 2 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import type SocketIO from 'socket.io';
import type { SSH, SSL, Server } from './shared/interfaces.js';
import { getCommand } from './server/command.js';
import { logger } from './shared/logger.js';
import { logger as getLogger } from './shared/logger.js';
import { login } from './server/login.js';
import { server } from './server/socketServer.js';
import { spawn } from './server/spawn.js';
Expand All @@ -29,6 +29,7 @@ export async function start(
forcessh: boolean = forceSSHDefault,
ssl?: SSL,
): Promise<SocketIO.Server> {
const logger = getLogger();
if (ssh.key) {
logger.warn(`!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! Password-less auth enabled using private key from ${ssh.key}.
Expand Down
2 changes: 1 addition & 1 deletion src/server/command/ssh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export function sshOptions(
): string[] {
const cmd = parseCommand(command, path);
const hostChecking = knownHosts !== '/dev/null' ? 'yes' : 'no';
logger.info(`Authentication Type: ${auth}`);
logger().info(`Authentication Type: ${auth}`);
let sshRemoteOptsBase = ['ssh', host, '-t'];
if (!isUndefined(config) && config !== '') {
sshRemoteOptsBase = sshRemoteOptsBase.concat(['-F', config]);
Expand Down
10 changes: 8 additions & 2 deletions src/server/socketServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export async function server(
ssl?: SSL,
): Promise<SocketIO.Server> {
const basePath = trim(base);
logger.info('Starting server', {
logger().info('Starting server', {
ssl,
port,
base,
Expand All @@ -30,7 +30,13 @@ export async function server(
.use(`${basePath}/web_modules`, serveStatic('web_modules'))
.use(`${basePath}/assets`, serveStatic('assets'))
.use(`${basePath}/client`, serveStatic('client'))
.use(winston.logger(logger))
.use(
winston.logger({
winstonInstance: logger(),
expressFormat: true,
level: 'http',
}),
)
.use(compression())
.use(favicon(basePath))
.use(redirect)
Expand Down
4 changes: 2 additions & 2 deletions src/server/socketServer/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ export const listen = (
socket(
!isUndefined(key) && !isUndefined(cert)
? https.createServer({ key, cert }, app).listen(port, host, () => {
logger.info('Server started', {
logger().info('Server started', {
port,
connection: 'https',
});
})
: http.createServer(app).listen(port, host, () => {
logger.info('Server started', {
logger().info('Server started', {
port,
connection: 'http',
});
Expand Down
3 changes: 2 additions & 1 deletion src/server/spawn.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import type SocketIO from 'socket.io';
import isUndefined from 'lodash/isUndefined.js';
import pty from 'node-pty';
import { logger } from '../shared/logger.js';
import { logger as getLogger } from '../shared/logger.js';
import { xterm } from './shared/xterm.js';
import { envVersion } from './spawn/env.js';

export async function spawn(
socket: SocketIO.Socket,
args: string[],
): Promise<void> {
const logger = getLogger();
const version = await envVersion();
const cmd = version >= 9 ? ['-S', ...args] : args;
logger.debug('Spawning PTTY', { cmd });
Expand Down
25 changes: 24 additions & 1 deletion src/shared/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ import path from 'path';
import JSON5 from 'json5';
import isUndefined from 'lodash/isUndefined.js';
import type { Arguments } from 'yargs';

import type winston from 'winston';
import type { Config, SSH, Server, SSL } from './interfaces';
import {
sshDefault,
serverDefault,
forceSSHDefault,
defaultCommand,
defaultLogLevel,
} from './defaults.js';

type confValue =
Expand All @@ -21,6 +22,7 @@ type confValue =
| SSH
| Server
| SSL;

/**
* Cast given value to boolean
*
Expand All @@ -41,6 +43,24 @@ function ensureBoolean(value: confValue): boolean {
}
}

function parseLogLevel(
confLevel: winston.level,
optsLevel: unknown,
): winston.level {
const logLevel = isUndefined(optsLevel) ? confLevel : `${optsLevel}`;
return [
'error',
'warn',
'info',
'http',
'verbose',
'debug',
'silly',
].includes(logLevel)
? (logLevel as winston.level)
: defaultLogLevel;
}

/**
* Load JSON5 config from file and merge with default args
* If no path is provided the default config is returned
Expand All @@ -55,6 +75,7 @@ export async function loadConfigFile(filepath?: string): Promise<Config> {
server: serverDefault,
command: defaultCommand,
forceSSH: forceSSHDefault,
logLevel: defaultLogLevel,
};
}
const content = await fs.readFile(path.resolve(filepath));
Expand All @@ -71,6 +92,7 @@ export async function loadConfigFile(filepath?: string): Promise<Config> {
? forceSSHDefault
: ensureBoolean(parsed.forceSSH),
ssl: parsed.ssl,
logLevel: parseLogLevel(defaultLogLevel, parsed.logLevel),
};
}

Expand Down Expand Up @@ -131,5 +153,6 @@ export function mergeCliConf(opts: Arguments, config: Config): Config {
? config.forceSSH
: ensureBoolean(opts['force-ssh']),
ssl: isUndefined(ssl.key) || isUndefined(ssl.cert) ? undefined : ssl,
logLevel: parseLogLevel(config.logLevel, opts['log-level']),
};
}
2 changes: 2 additions & 0 deletions src/shared/defaults.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { SSH, Server } from './interfaces';
import { isDev } from './env.js';

export const sshDefault: SSH = {
user: process.env.SSHUSER || '',
Expand All @@ -22,3 +23,4 @@ export const serverDefault: Server = {

export const forceSSHDefault = process.env.FORCESSH === 'true' || false;
export const defaultCommand = process.env.COMMAND || 'login';
export const defaultLogLevel = isDev ? 'debug' : 'http';
3 changes: 3 additions & 0 deletions src/shared/interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type winston from 'winston';

export interface SSH {
[s: string]: string | number | boolean | undefined;
user: string;
Expand Down Expand Up @@ -35,5 +37,6 @@ export interface Config {
server: Server;
forceSSH: boolean;
command: string;
logLevel: winston.level;
ssl?: SSL;
}
22 changes: 19 additions & 3 deletions src/shared/logger.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import winston from 'winston';

import { isDev } from './env.js';
import { defaultLogLevel } from './defaults.js';

const { combine, timestamp, label, simple, json, colorize } = winston.format;

Expand All @@ -13,12 +13,28 @@ const dev = combine(

const prod = combine(label({ label: 'Wetty' }), timestamp(), json());

export const logger = winston.createLogger({
let globalLogger = winston.createLogger({
format: isDev ? dev : prod,
transports: [
new winston.transports.Console({
level: isDev ? 'debug' : 'info',
level: defaultLogLevel,
handleExceptions: true,
}),
],
});

export function setLevel(level: winston.level): void {
globalLogger = winston.createLogger({
format: isDev ? dev : prod,
transports: [
new winston.transports.Console({
level,
handleExceptions: true,
}),
],
});
}

export function logger(): winston.Logger {
return globalLogger;
}

0 comments on commit 0b5262b

Please sign in to comment.