Code coverage report for node/src/log/JsonLog.ts

Statements: 70.59% (12 / 17)      Branches: 57.89% (11 / 19)      Functions: 66.67% (4 / 6)      Lines: 70.59% (12 / 17)      Ignored: none     

All files » node/src/log/ » JsonLog.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 591 1       1     2       2                                       2             2       2 2 2 2     2                  
import {Env, Log, LogConfig, LogLevel, MessageContext} from '@btilford/ts-base-core';
import {StdLogOptions, StdOutLog} from './StdOutLog';
import {Writable} from 'stream';
 
 
export class JsonLog extends StdOutLog {
 
  constructor(name: string, config: LogConfig, parent?: Log, env?: Env, stdout?: Writable, stderr?: Writable) {
    super(name, config, parent, env, stdout, stderr);
  }
 
  static create(options: StdLogOptions): JsonLog {
    return new JsonLog(
      options.name || '',
      LogConfig.create(options.config),
      options.parent,
      options.env,
      options.stdout,
      options.stderr
    );
  }
 
  extend(name: string, config?: LogConfig): JsonLog {
    return new JsonLog(name, config || this.config, this, this.env, this.stdout, this.stderr);
  }
 
  copy(name: string, config?: LogConfig): JsonLog {
    return new JsonLog(name, config || this.config, undefined, this.env, this.stdout, this.stderr);
  }
 
  formatJson(level: LogLevel, renderedMessage: string, message: MessageContext): string {
 
    const obj = {
      level: level.name,
      severity: level.severity,
      message: renderedMessage,
      timestamp: message.data?.ts || message.data?.timestamp || new Date(),
      context: message.data
    };
    return JSON.stringify(obj);
  }
 
  protected _write(level: LogLevel, message: MessageContext, ...args: unknown[]): void | Error {
    try {
      const outputMessage = this.createOutputString(level, message, ...args);
      const output = this.formatJson(level, outputMessage, message);
      Iif (level.gte(LogLevel.WARN)) {
        this.stderr.write(output);
      } else {
        this.stdout.write(output);
      }
 
    } catch (error) {
      console.error('Error writing message', message);
      return error;
    }
  }
}