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 { 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() {
// 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() {
console.log('🔧 Demonstrating custom proxy source...');
logger.info('🔧 Demonstrating custom proxy source...');
const customSources : ProxySource[] = [
{
@ -96,12 +100,16 @@ async function demonstrateCustomProxySource() {
protocol: 'http'
}
];
try {
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) {
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,
demonstrateCustomProxySource
};
// Execute the demo with enhanced logging
logger.info('🚀 Starting enhanced proxy demo...');
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 (import.meta.main) {

View file

@ -440,7 +440,6 @@ export class ProxyService {
*/
private async validateProxiesInBackground(proxies: ProxyConfig[]): Promise<void> {
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 chunks = this.chunkArray(proxies, concurrency);

View file

@ -34,7 +34,6 @@ function createTransports(serviceName: string, options?: {
} = options || {};
const targets: any[] = [];
// Console transport with pretty formatting
if (enableConsole) {
targets.push({
@ -43,11 +42,12 @@ function createTransports(serviceName: string, options?: {
options: {
colorize: true,
translateTime: 'yyyy-mm-dd HH:MM:ss.l',
ignore: 'pid,hostname',
// messageFormat: '[{service}] {msg}',
// errorLikeObjectKeys: ['err', 'error'], // Tell pino-pretty these are error objects
// errorProps: 'message,stack,name,code', // Which error properties to show
singleLine: true,
ignore: 'pid,hostname,environment,version,service',
messageFormat: '[{service}] {msg}',
errorLikeObjectKeys: ['err', 'error'],
errorProps: 'message,stack,name,code',
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 serviceName: string;
private context: LogContext;
constructor(serviceName: string, context: LogContext = {}, options?: {
level?: LogLevel;
enableLoki?: boolean;
@ -187,7 +186,9 @@ export class Logger {
this.serviceName = serviceName;
this.context = context;
this.pino = createLogger(serviceName, options);
} /**
}
/**
* Flexible log method that accepts string or object messages
*/
log(level: LogLevel, message: string | object, metadata?: LogMetadata): void {
@ -199,7 +200,19 @@ export class Logger {
if (typeof message === 'string') {
(this.pino as any)[level](logData, message);
} 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 {
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 {
const logData: LogMetadata = { ...metadata };
if (error) {
if (error instanceof Error) {
logData.error = {
name: error.name,
message: error.message,
stack: loggingConfig.LOG_ERROR_STACK ? error.stack : undefined
};
// Use 'err' key for pino-pretty compatibility
logData.err = error;
} else {
logData.error = error;
}