@livy/ansi-line-formatter
Version: 
Formats Livy log records as single lines with terminal highlighting
91 lines (90 loc) • 2.58 kB
JavaScript
import { LineFormatter } from '@livy/line-formatter';
import { isEmpty } from '@livy/util/lib/helpers.mjs';
import chalk from 'chalk';
const emphasize = require('emphasize');
/**
 * Formats log records as single lines with terminal highlighting
 */
export class AnsiLineFormatter extends LineFormatter {
    constructor({ decorated, ...options } = {}) {
        super(options);
        this.decorated = decorated;
    }
    /**
     * @inheritdoc
     */
    formatDatetime(datetime) {
        const timestamp = super.formatDatetime(datetime);
        if (this.shouldDecorate()) {
            return chalk.dim(timestamp);
        }
        else {
            return timestamp;
        }
    }
    /**
     * @inheritdoc
     */
    formatLevel(level) {
        const formatted = super.formatLevel(level);
        if (!this.shouldDecorate()) {
            return formatted;
        }
        else {
            let color;
            switch (level) {
                case 'emergency':
                    color = 'red';
                    break;
                case 'alert':
                    color = 'red';
                    break;
                case 'critical':
                    color = 'red';
                    break;
                case 'error':
                    color = 'red';
                    break;
                case 'warning':
                    color = 'yellow';
                    break;
                case 'notice':
                    color = 'blue';
                    break;
                case 'info':
                    color = 'blue';
                    break;
                case 'debug':
                    color = 'blue.dim';
                    break;
                // istanbul ignore next: This should never happen, but is included for type safety
                default:
                    return formatted;
            }
            return chalk `{${color} ${formatted}}`;
        }
    }
    /**
     * @inheritdoc
     */
    formatData(object, ignoreEmpty) {
        if (isEmpty(object) && ignoreEmpty) {
            return '';
        }
        const stringified = super.formatData(object);
        if (this.shouldDecorate()) {
            return emphasize.highlight('json', stringified).value;
        }
        else {
            return stringified;
        }
    }
    /**
     * Check whether the formatter should use ANSI codes to decorate log records
     */
    shouldDecorate() {
        return !!(typeof this.decorated !== 'undefined'
            ? this.decorated
            : chalk.supportsColor);
    }
}