github.com/kaleido-io/firefly@v0.0.0-20210622132723-8b4b6aacb971/kat/src/lib/logging.ts (about) 1 // Copyright © 2021 Kaleido, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 "use strict"; 16 17 const LEVEL_NONE = 0; 18 const LEVEL_ERROR = 1; 19 const LEVEL_WARN = 2; 20 const LEVEL_INFO = 3; 21 const LEVEL_DEBUG = 4; 22 const LEVEL_TRACE = 5; 23 24 const LEVEL_TAGS = { 25 [LEVEL_NONE]: 'NONE', 26 [LEVEL_ERROR]: 'ERROR', 27 [LEVEL_WARN]: 'WARN ', 28 [LEVEL_INFO]: 'INFO ', 29 [LEVEL_DEBUG]: 'DEBUG', 30 [LEVEL_TRACE]: 'TRACE', 31 }; 32 33 let logLevel = LEVEL_ERROR; 34 35 export function setLogLevel(level?: string) { 36 if (!level) level = process.env.LOG_LEVEL || 'info'; 37 for (let [l,t] of Object.entries(LEVEL_TAGS)) { 38 if (t.trim().toLowerCase() === level.trim().toLowerCase()) { 39 logLevel = Number(l); 40 } 41 } 42 } 43 44 export class Logger { 45 46 constructor(private loggerName?: string) {} 47 48 error(...args: any[]) { logLevel >= LEVEL_ERROR && this.log('ERROR', ...args); } 49 warn(...args: any[]) { logLevel >= LEVEL_WARN && this.log('WARN ', ...args); } 50 info(...args: any[]) { logLevel >= LEVEL_INFO && this.log('INFO ', ...args); } 51 debug(...args: any[]) { logLevel >= LEVEL_DEBUG && this.log('DEBUG', ...args); } 52 trace(...args: any[]) { logLevel >= LEVEL_TRACE && this.log('TRACE', ...args); } 53 54 private log(level: string, ...args: any[]) { 55 const logArgs = []; 56 for (const arg of args) { 57 // Special handling of axios errors to avoid massive dumps in log 58 if (arg?.isAxiosError) { 59 let data = arg.response?.data; 60 data = data?.on ? '[stream]' : JSON.stringify(data); 61 logArgs.push(`HTTP [${arg.response?.status}] ${arg.message}: ${data}`) 62 } else { 63 logArgs.push(arg); 64 } 65 } 66 console.log(`${new Date().toISOString()} [${level}]:`, ...logArgs, this.loggerName); 67 } 68 69 } 70 71 setLogLevel();