-
Notifications
You must be signed in to change notification settings - Fork 2.2k
centralized logging for BWS and BCN. #4137
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tmcollins4
wants to merge
1
commit into
bitpay:master
Choose a base branch
from
tmcollins4:add-bitcore-logging-package
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| { | ||
| "name": "@bitpay-labs/bitcore-logging", | ||
| "description": "Centralized logging for Bitcore services", | ||
| "author": "BitPay Inc", | ||
| "version": "11.6.6", | ||
| "engines": { | ||
| "node": ">=22.0.0" | ||
| }, | ||
| "keywords": [ | ||
| "bitcore", | ||
| "logging", | ||
| "typescript", | ||
| "winston" | ||
| ], | ||
| "license": "MIT", | ||
| "main": "ts_build/src/index.js", | ||
| "types": "./ts_build/src/index.d.ts", | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "https://github.com/bitpay/bitcore/tree/master/packages/bitcore-logging" | ||
| }, | ||
| "scripts": { | ||
| "build": "tsc", | ||
| "build:prod": "tsc -p tsconfig.prod.json", | ||
| "clean": "rm -rf ts_build", | ||
| "compile": "npm run clean && npm run build", | ||
| "test": "npm run compile && mocha --exit -r tsx 'test/**/*.test.ts'", | ||
| "test:ci": "TEST_LOG_LEVEL=none npm run test", | ||
| "lint": "eslint .", | ||
| "fix:errors": "eslint --fix --quiet .", | ||
| "fix:all": "eslint --fix .", | ||
| "fix": "npm run fix:errors", | ||
| "precommit": "npm run lint" | ||
| }, | ||
| "dependencies": { | ||
| "winston": "3.3.3" | ||
| }, | ||
| "devDependencies": { | ||
| "@types/chai": "^5.2.2", | ||
| "@types/mocha": "^5.2.0", | ||
| "@types/node": "^22.10.10", | ||
| "chai": "^5.2.0", | ||
| "mocha": "^5.2.0", | ||
| "tsx": "^4.21.0", | ||
| "typescript": "^5.7.3" | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| import path from 'path'; | ||
| import * as winston from 'winston'; | ||
| import { consoleFormat, httpFormat } from './formatters'; | ||
| import { LoggerConfig } from './types'; | ||
|
|
||
| /** | ||
| * Build the transport array for a given config. | ||
| * Reads environment variables using the config prefix: | ||
| * {PREFIX}_LOG_LEVEL, {PREFIX}_LOG_HTTP_HOST, etc. | ||
| */ | ||
| export function getTransports(config: LoggerConfig): winston.transport[] { | ||
| const prefix = config.prefix; | ||
| const defaultLevel = config.defaultLevel || 'info'; | ||
| const logLevel = config.debug ? 'debug' : (process.env[`${prefix}_LOG_LEVEL`] || defaultLevel); | ||
| const lowerPrefix = prefix.toLowerCase(); | ||
|
|
||
| const result: winston.transport[] = [ | ||
| new winston.transports.Console({ | ||
| level: logLevel, | ||
| format: consoleFormat() | ||
| }) | ||
| ]; | ||
|
|
||
| const httpHost = process.env[`${prefix}_LOG_HTTP_HOST`]; | ||
| if (httpHost) { | ||
| const scriptName = process.argv[1] ? path.parse(process.argv[1]).name : 'unknown'; | ||
| const defaultPath = `${lowerPrefix}.${scriptName}`; | ||
| const tag = process.env[`${prefix}_LOG_HTTP_TAG`] || defaultPath; | ||
|
|
||
| result.push(new winston.transports.Http({ | ||
| level: process.env[`${prefix}_LOG_HTTP_LEVEL`] || logLevel, | ||
| host: httpHost, | ||
| port: parseInt(process.env[`${prefix}_LOG_HTTP_PORT`] as string) || undefined, | ||
| path: process.env[`${prefix}_LOG_HTTP_PATH`] || defaultPath, | ||
| headers: { | ||
| 'Content-Type': 'application/json' | ||
| }, | ||
| format: httpFormat(tag) | ||
| })); | ||
| } | ||
|
|
||
| return result; | ||
| } | ||
|
|
||
| /** | ||
| * Create a Winston logger configured via environment variables. | ||
| * | ||
| * Usage: | ||
| * const logger = createLogger({ prefix: 'BCN' }); | ||
| * // reads BCN_LOG_LEVEL, BCN_LOG_HTTP_HOST, etc. | ||
| */ | ||
| export function createLogger(config: LoggerConfig): winston.Logger { | ||
| const transports = getTransports(config); | ||
| return winston.createLogger({ transports }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import util from 'util'; | ||
| import * as winston from 'winston'; | ||
|
|
||
| export const PerformanceTracker: Record<string, { time: number; count: number; avg: number; max: number }> = {}; | ||
|
|
||
| let _debugEnabled = false; | ||
| let _logger: winston.Logger | null = null; | ||
|
|
||
| /** | ||
| * Initialize the Loggify decorators with a logger and debug flag. | ||
| * Must be called before using LoggifyClass/LoggifyFunction/LoggifyObject. | ||
| */ | ||
| export function initLoggify(logger: winston.Logger, debug: boolean): void { | ||
| if (_logger) { | ||
| _logger.warn('initLoggify called more than once — overwriting existing logger'); | ||
| } | ||
| _logger = logger; | ||
| _debugEnabled = debug; | ||
| } | ||
|
|
||
| export function SavePerformance(logPrefix: string, startTime: Date, endTime: Date): void { | ||
| const totalTime = endTime.getTime() - startTime.getTime(); | ||
| if (!PerformanceTracker[logPrefix]) { | ||
| PerformanceTracker[logPrefix] = { | ||
| time: totalTime, | ||
| count: 1, | ||
| avg: totalTime, | ||
| max: totalTime | ||
| }; | ||
| } else { | ||
| PerformanceTracker[logPrefix].time += totalTime; | ||
| PerformanceTracker[logPrefix].count++; | ||
| PerformanceTracker[logPrefix].avg = PerformanceTracker[logPrefix].time / PerformanceTracker[logPrefix].count; | ||
| PerformanceTracker[logPrefix].max = Math.max(totalTime, PerformanceTracker[logPrefix].max); | ||
| } | ||
| } | ||
|
|
||
| export function LoggifyClass<T extends new (...args: any[]) => object>(aClass: T) { | ||
| if (!_debugEnabled || !_logger) { | ||
| return aClass; | ||
| } | ||
| const logger = _logger; | ||
| return class extends aClass { | ||
| constructor(...args: any[]) { | ||
| super(...args); | ||
| logger.debug(`Loggifying ${aClass.name} with args:: ${util.inspect(args)}`); | ||
| for (const prop of Object.getOwnPropertyNames(aClass.prototype)) { | ||
| if (typeof this[prop] === 'function') { | ||
| logger.debug(`Loggifying ${aClass.name}::${prop}`); | ||
| this[prop] = LoggifyFunction(this[prop], `${aClass.name}::${prop}`, this); | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| export function LoggifyFunction(fn: (...args: any[]) => any, logPrefix: string = '', bind?: any) { | ||
| if (!_debugEnabled || !_logger) { | ||
| return fn as (...methodargs: any[]) => any; | ||
| } | ||
| const logger = _logger; | ||
| let copy = fn; | ||
| if (bind) { | ||
| copy = copy.bind(bind); | ||
| } | ||
| return function(...methodargs: any[]) { | ||
| const startTime = new Date(); | ||
| logger.debug(`${logPrefix}::called::`); | ||
| const returnVal = copy(...methodargs); | ||
| if (returnVal && returnVal.then) { | ||
| returnVal | ||
| .catch((err: any) => { | ||
| logger.error(`${logPrefix}::catch::${err}`); | ||
| }) | ||
| .then((data: any) => { | ||
| logger.debug(`${logPrefix}::resolved::`); | ||
| SavePerformance(logPrefix, startTime, new Date()); | ||
| return data; | ||
| }); | ||
| } else { | ||
| SavePerformance(logPrefix, startTime, new Date()); | ||
| logger.debug(`${logPrefix}::returned::`); | ||
| } | ||
| return returnVal; | ||
| }; | ||
| } | ||
|
|
||
| export function LoggifyObject(obj: any, logPrefix: string = '', bind?: any) { | ||
| if (!_debugEnabled || !_logger) { | ||
| return obj; | ||
| } | ||
| const logger = _logger; | ||
| for (const prop of Object.getOwnPropertyNames(obj)) { | ||
| if (typeof obj[prop] === 'function') { | ||
| logger.debug(`Loggifying ${logPrefix}::${prop}`); | ||
| obj[prop] = LoggifyFunction(obj[prop], `${logPrefix}::${prop}`, bind); | ||
| } | ||
| } | ||
| return obj; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| import * as winston from 'winston'; | ||
|
|
||
| /** | ||
| * Shared console format: colorize + prettyPrint + splat + simple + custom printf. | ||
| * Matches the existing BCN/BWS console output format. | ||
| */ | ||
| export function consoleFormat(): winston.Logform.Format { | ||
| return winston.format.combine( | ||
| winston.format.colorize(), | ||
| winston.format.prettyPrint(), | ||
| winston.format.splat(), | ||
| winston.format.simple(), | ||
| winston.format.printf(function(info) { | ||
| // fallback in case the above formatters don't work. | ||
| // eg: logger.log({ some: 'object' }) | ||
| if (typeof info.message === 'object') { | ||
| info.message = JSON.stringify(info.message, null, 4); | ||
| } | ||
| return `${info.level} :: ${new Date().toISOString()} :: ${info.message}`; | ||
| }) | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Shared HTTP transport format with a tag field for log aggregation. | ||
| */ | ||
| export function httpFormat(tag: string): winston.Logform.Format { | ||
| return winston.format.combine( | ||
| winston.format.splat(), | ||
| winston.format.simple(), | ||
| winston.format.printf(info => { | ||
| // fallback in case the above formatters don't work. | ||
| // eg: logger.log({ some: 'object' }) | ||
| if (typeof info.message === 'object') { | ||
| info.message = JSON.stringify(info.message, null, 4); | ||
| } | ||
| return JSON.stringify({ tag, ...info }); | ||
| }) | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| export { createLogger, getTransports } from './create'; | ||
| export { consoleFormat, httpFormat } from './formatters'; | ||
| export { formatTimestamp, timestamp } from './timestamp'; | ||
| export { | ||
| initLoggify, | ||
| LoggifyClass, | ||
| LoggifyFunction, | ||
| LoggifyObject, | ||
| SavePerformance, | ||
| PerformanceTracker | ||
| } from './decorators'; | ||
| export { LoggerConfig } from './types'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| const timezone = new Date() | ||
| .toLocaleString('en-US', { timeZoneName: 'short' }) | ||
| .split(' ') | ||
| .pop(); | ||
|
|
||
| export const formatTimestamp = (date: Date): string => | ||
| `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date | ||
| .getDate() | ||
| .toString() | ||
| .padStart(2, '0')} ${date | ||
| .getHours() | ||
| .toString() | ||
| .padStart(2, '0')}:${date | ||
| .getMinutes() | ||
| .toString() | ||
| .padStart(2, '0')}:${date | ||
| .getSeconds() | ||
| .toString() | ||
| .padStart(2, '0')}.${date | ||
| .getMilliseconds() | ||
| .toString() | ||
| .padStart(3, '0')} ${timezone}`; | ||
|
|
||
| export const timestamp = (): string => formatTimestamp(new Date()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| export interface LoggerConfig { | ||
| /** Environment variable prefix, e.g. 'BCN' reads BCN_LOG_LEVEL, BCN_LOG_HTTP_HOST, etc. */ | ||
| prefix: string; | ||
| /** Default log level when env var is not set (default: 'info') */ | ||
| defaultLevel?: string; | ||
| /** Force debug log level (e.g. from a --DEBUG CLI flag) */ | ||
| debug?: boolean; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| import { expect } from 'chai'; | ||
| import { createLogger, getTransports } from '../src/create'; | ||
|
|
||
| describe('createLogger', () => { | ||
| const originalEnv = process.env; | ||
|
|
||
| beforeEach(() => { | ||
| process.env = { ...originalEnv }; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| process.env = originalEnv; | ||
| }); | ||
|
|
||
| it('should create a logger with console transport', () => { | ||
| const logger = createLogger({ prefix: 'TEST' }); | ||
| expect(logger).to.exist; | ||
| expect(logger.info).to.be.a('function'); | ||
| expect(logger.error).to.be.a('function'); | ||
| expect(logger.debug).to.be.a('function'); | ||
| expect(logger.warn).to.be.a('function'); | ||
| }); | ||
|
|
||
| it('should use defaultLevel when env var is not set', () => { | ||
| delete process.env.TEST_LOG_LEVEL; | ||
| const transports = getTransports({ prefix: 'TEST', defaultLevel: 'warn' }); | ||
| expect(transports).to.have.length(1); | ||
| expect((transports[0] as any).level).to.equal('warn'); | ||
| }); | ||
|
|
||
| it('should default to info when no defaultLevel and no env var', () => { | ||
| delete process.env.TEST_LOG_LEVEL; | ||
| const transports = getTransports({ prefix: 'TEST' }); | ||
| expect((transports[0] as any).level).to.equal('info'); | ||
| }); | ||
|
|
||
| it('should read log level from env var using prefix', () => { | ||
| process.env.TEST_LOG_LEVEL = 'error'; | ||
| const transports = getTransports({ prefix: 'TEST' }); | ||
| expect((transports[0] as any).level).to.equal('error'); | ||
| }); | ||
|
|
||
| it('should override to debug when debug flag is true', () => { | ||
| process.env.TEST_LOG_LEVEL = 'error'; | ||
| const transports = getTransports({ prefix: 'TEST', debug: true }); | ||
| expect((transports[0] as any).level).to.equal('debug'); | ||
| }); | ||
|
|
||
| it('should only have console transport when no HTTP host set', () => { | ||
| delete process.env.TEST_LOG_HTTP_HOST; | ||
| const transports = getTransports({ prefix: 'TEST' }); | ||
| expect(transports).to.have.length(1); | ||
| }); | ||
|
|
||
| it('should add HTTP transport when HTTP host is set', () => { | ||
| process.env.TEST_LOG_HTTP_HOST = 'localhost'; | ||
| const transports = getTransports({ prefix: 'TEST' }); | ||
| expect(transports).to.have.length(2); | ||
| }); | ||
|
|
||
| it('should read HTTP port from env var', () => { | ||
| process.env.TEST_LOG_HTTP_HOST = 'localhost'; | ||
| process.env.TEST_LOG_HTTP_PORT = '9200'; | ||
| const transports = getTransports({ prefix: 'TEST' }); | ||
| expect(transports).to.have.length(2); | ||
| }); | ||
|
|
||
| it('should work with different prefixes', () => { | ||
| process.env.BCN_LOG_LEVEL = 'debug'; | ||
| process.env.BWS_LOG_LEVEL = 'warn'; | ||
|
|
||
| const bcnTransports = getTransports({ prefix: 'BCN' }); | ||
| const bwsTransports = getTransports({ prefix: 'BWS' }); | ||
|
|
||
| expect((bcnTransports[0] as any).level).to.equal('debug'); | ||
| expect((bwsTransports[0] as any).level).to.equal('warn'); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Update to 11.7.0 to fix the build failing.