fixed logger

This commit is contained in:
Bojan Kucera 2025-06-07 09:44:17 -04:00
parent 4709887fef
commit e8485dd140
3 changed files with 48 additions and 23 deletions

View file

@ -1,7 +1,11 @@
import { proxyService, ProxySource } from './services/proxy.service.js'; import { proxyService, ProxySource } from './services/proxy.service.js';
import { getLogger } from '@stock-bot/logger';
// Initialize logger for the demo
const logger = getLogger('proxy-demo');
/** /**
* Example usage of the ProxyService * Example usage of the ProxyService with enhanced logging
*/ */
// async function demonstrateProxyService() { // async function demonstrateProxyService() {
// console.log('🚀 Starting Proxy Service Demo...'); // console.log('🚀 Starting Proxy Service Demo...');
@ -85,10 +89,10 @@ import { proxyService, ProxySource } from './services/proxy.service.js';
// } // }
/** /**
* Example: Custom proxy source * Example: Custom proxy source with enhanced logging
*/ */
async function demonstrateCustomProxySource() { async function demonstrateCustomProxySource() {
console.log('🔧 Demonstrating custom proxy source...'); logger.info('🔧 Demonstrating custom proxy source...');
const customSources : ProxySource[] = [ const customSources : ProxySource[] = [
{ {
@ -96,12 +100,16 @@ async function demonstrateCustomProxySource() {
protocol: 'http' protocol: 'http'
} }
]; ];
try { try {
const count = await proxyService.scrapeProxies(customSources); const count = await proxyService.scrapeProxies(customSources);
console.log(`✅ Scraped ${count} proxies from custom source`); logger.info(`✅ Scraped ${count} proxies from custom source`, {
count,
sourceCount: customSources.length
});
} catch (error) { } catch (error) {
console.error('❌ Custom source scraping failed:', error); logger.error('❌ Custom source scraping failed', error, {
sourceUrls: customSources.map(s => s.url)
});
} }
} }
@ -110,7 +118,16 @@ export {
// demonstrateProxyService, // demonstrateProxyService,
demonstrateCustomProxySource demonstrateCustomProxySource
}; };
// Execute the demo with enhanced logging
logger.info('🚀 Starting enhanced proxy demo...');
demonstrateCustomProxySource() demonstrateCustomProxySource()
.then(() => {
logger.info('🎉 Proxy demo completed successfully!');
})
.catch((error) => {
logger.error('💥 Proxy demo failed', error);
});
// If this file is run directly, execute the demo // If this file is run directly, execute the demo
// if (import.meta.main) { // if (import.meta.main) {

View file

@ -440,7 +440,6 @@ export class ProxyService {
*/ */
private async validateProxiesInBackground(proxies: ProxyConfig[]): Promise<void> { private async validateProxiesInBackground(proxies: ProxyConfig[]): Promise<void> {
this.logger.info('Starting background proxy validation', { count: proxies.length }); this.logger.info('Starting background proxy validation', { count: proxies.length });
this.logger.error('Background validation is not implemented yet, this is a placeholder function', { error: { message: 'Background validation not implemented' } });
const concurrency = 50; // Process 50 proxies concurrently const concurrency = 50; // Process 50 proxies concurrently
const chunks = this.chunkArray(proxies, concurrency); const chunks = this.chunkArray(proxies, concurrency);

View file

@ -34,7 +34,6 @@ function createTransports(serviceName: string, options?: {
} = options || {}; } = options || {};
const targets: any[] = []; const targets: any[] = [];
// Console transport with pretty formatting // Console transport with pretty formatting
if (enableConsole) { if (enableConsole) {
targets.push({ targets.push({
@ -43,11 +42,12 @@ function createTransports(serviceName: string, options?: {
options: { options: {
colorize: true, colorize: true,
translateTime: 'yyyy-mm-dd HH:MM:ss.l', translateTime: 'yyyy-mm-dd HH:MM:ss.l',
ignore: 'pid,hostname', ignore: 'pid,hostname,environment,version,service',
// messageFormat: '[{service}] {msg}', messageFormat: '[{service}] {msg}',
// errorLikeObjectKeys: ['err', 'error'], // Tell pino-pretty these are error objects errorLikeObjectKeys: ['err', 'error'],
// errorProps: 'message,stack,name,code', // Which error properties to show errorProps: 'message,stack,name,code',
singleLine: true, singleLine: false, // Allow multiline for better metadata display
hideObject: false, // Show metadata objects
} }
}); });
} }
@ -177,7 +177,6 @@ export class Logger {
private pino: pino.Logger; private pino: pino.Logger;
private serviceName: string; private serviceName: string;
private context: LogContext; private context: LogContext;
constructor(serviceName: string, context: LogContext = {}, options?: { constructor(serviceName: string, context: LogContext = {}, options?: {
level?: LogLevel; level?: LogLevel;
enableLoki?: boolean; enableLoki?: boolean;
@ -187,7 +186,9 @@ export class Logger {
this.serviceName = serviceName; this.serviceName = serviceName;
this.context = context; this.context = context;
this.pino = createLogger(serviceName, options); this.pino = createLogger(serviceName, options);
} /** }
/**
* Flexible log method that accepts string or object messages * Flexible log method that accepts string or object messages
*/ */
log(level: LogLevel, message: string | object, metadata?: LogMetadata): void { log(level: LogLevel, message: string | object, metadata?: LogMetadata): void {
@ -199,7 +200,19 @@ export class Logger {
if (typeof message === 'string') { if (typeof message === 'string') {
(this.pino as any)[level](logData, message); (this.pino as any)[level](logData, message);
} else { } else {
(this.pino as any)[level]({ ...logData, ...message }); // For object messages, use the message object as the main log data
// and add metadata without overwriting properties from the message
const messageObj = message as Record<string, any>;
const combinedData = { ...logData };
// Add message properties that don't conflict with metadata
Object.keys(messageObj).forEach(key => {
if (!(key in combinedData)) {
combinedData[key] = messageObj[key];
}
});
(this.pino as any)[level](combinedData, messageObj.msg || messageObj.message || 'Object log');
} }
} }
@ -239,20 +252,16 @@ export class Logger {
warn(message: string | object, metadata?: LogMetadata): void { warn(message: string | object, metadata?: LogMetadata): void {
this.log('warn', message, metadata); this.log('warn', message, metadata);
} }
/** /**
* Error level logging * Error level logging with proper pino-pretty formatting
*/ */
error(message: string | object, error?: Error | any, metadata?: LogMetadata): void { error(message: string | object, error?: Error | any, metadata?: LogMetadata): void {
const logData: LogMetadata = { ...metadata }; const logData: LogMetadata = { ...metadata };
if (error) { if (error) {
if (error instanceof Error) { if (error instanceof Error) {
logData.error = { // Use 'err' key for pino-pretty compatibility
name: error.name, logData.err = error;
message: error.message,
stack: loggingConfig.LOG_ERROR_STACK ? error.stack : undefined
};
} else { } else {
logData.error = error; logData.error = error;
} }