var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
/**
 * Copyright (C) 2024 Hedera Hashgraph, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the ""License"");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an ""AS IS"" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import * as winston from 'winston';
import { v4 as uuidv4 } from 'uuid';
import * as util from 'util';
import chalk from 'chalk';
import path from 'path';
import * as constants from './constants.js';
import { inject, injectable } from 'tsyringe-neo';
import { patchInject } from './container_helper.js';
const customFormat = winston.format.combine(winston.format.label({ label: 'SOLO', message: false }), winston.format.splat(), 
// include timestamp in logs
winston.format.timestamp(), winston.format.ms(), 
// add label metadata
winston.format.label({ label: '' }), 
// convert levels to upper case
winston.format(data => {
    data.level = data.level.toUpperCase();
    return data;
})(), 
// use custom format TIMESTAMP [LABEL] LEVEL: MESSAGE
winston.format.printf(data => `${data.timestamp}|${data.level}| ${data.message}`), 
// Ignore log messages if they have { private: true }
winston.format(data => (data.private ? false : data))());
let SoloLogger = class SoloLogger {
    devMode;
    winstonLogger;
    traceId;
    /**
     * @param logLevel - the log level to use
     * @param devMode - if true, show full stack traces in error messages
     */
    constructor(logLevel, devMode) {
        this.devMode = devMode;
        logLevel = patchInject(logLevel, 'logLevel', this.constructor.name);
        this.devMode = patchInject(devMode, 'devMode', this.constructor.name);
        this.nextTraceId();
        this.winstonLogger = winston.createLogger({
            level: logLevel,
            format: winston.format.combine(customFormat, winston.format.json()),
            transports: [new winston.transports.File({ filename: path.join(constants.SOLO_LOGS_DIR, 'solo.log') })],
        });
    }
    setDevMode(devMode) {
        this.debug(`dev mode logging: ${devMode}`);
        this.devMode = devMode;
    }
    setLevel(level) {
        // @ts-ignore
        this.winstonLogger.setLevel(level);
    }
    nextTraceId() {
        this.traceId = uuidv4();
    }
    prepMeta(meta = {}) {
        meta.traceId = this.traceId;
        return meta;
    }
    showUser(msg, ...args) {
        console.log(util.format(msg, ...args));
        this.info(util.format(msg, ...args));
    }
    showUserError(err) {
        const stack = [{ message: err.message, stacktrace: err.stack }];
        if (err.cause) {
            let depth = 0;
            let cause = err.cause;
            while (cause !== undefined && depth < 10) {
                if (cause.stack) {
                    stack.push({ message: cause.message, stacktrace: cause.stack });
                }
                cause = cause.cause;
                depth += 1;
            }
        }
        console.log(chalk.red('*********************************** ERROR *****************************************'));
        if (this.devMode) {
            let prefix = '';
            let indent = '';
            stack.forEach(s => {
                console.log(indent + prefix + chalk.yellow(s.message));
                console.log(indent + chalk.gray(s.stacktrace) + '\n');
                indent += ' ';
                prefix += 'Caused by: ';
            });
        }
        else {
            const lines = err.message.split('\n');
            lines.forEach(line => {
                console.log(chalk.yellow(line));
            });
        }
        console.log(chalk.red('***********************************************************************************'));
        this.error(err.message, err);
    }
    error(msg, ...args) {
        this.winstonLogger.error(msg, ...args, this.prepMeta());
    }
    warn(msg, ...args) {
        this.winstonLogger.warn(msg, ...args, this.prepMeta());
    }
    info(msg, ...args) {
        this.winstonLogger.info(msg, ...args, this.prepMeta());
    }
    debug(msg, ...args) {
        this.winstonLogger.debug(msg, ...args, this.prepMeta());
    }
    showList(title, items = []) {
        this.showUser(chalk.green(`\n *** ${title} ***`));
        this.showUser(chalk.green('-------------------------------------------------------------------------------'));
        if (items.length > 0) {
            items.forEach(name => this.showUser(chalk.cyan(` - ${name}`)));
        }
        else {
            this.showUser(chalk.blue('[ None ]'));
        }
        this.showUser('\n');
        return true;
    }
    showJSON(title, obj) {
        this.showUser(chalk.green(`\n *** ${title} ***`));
        this.showUser(chalk.green('-------------------------------------------------------------------------------'));
        console.log(JSON.stringify(obj, null, ' '));
    }
};
SoloLogger = __decorate([
    injectable(),
    __param(0, inject('logLevel')),
    __param(1, inject('devMode')),
    __metadata("design:paramtypes", [String, Boolean])
], SoloLogger);
export { SoloLogger };
export function NewLogger(level = 'debug', devMode = false) {
    return new SoloLogger(level, devMode);
}
//# sourceMappingURL=logging.js.map