写一个代理console.log的方法

function createLogProxy(prefix = '') {
  const originalLog = console.log;

  return function(...args) {
    // Add timestamp
    const timestamp = new Date().toLocaleTimeString();

    // Handle different data types for logging
    const formattedArgs = args.map(arg => {
      if (typeof arg === 'object') {
        try {
          return JSON.stringify(arg, null, 2); // Pretty print objects
        } catch (e) {
          return '[Circular Object]'; // Handle circular references
        }
      } else if (typeof arg === 'function') {
        return arg.toString();
      } else {
        return arg;
      }
    });


    originalLog(`[${timestamp}] ${prefix}`, ...formattedArgs);


  };
}


// Example usage:

// Create a proxy with a prefix
const myLogger = createLogProxy('[My App]');

// Use the proxy for logging
myLogger('This is a test log.');
myLogger({ a: 1, b: 'hello' });
myLogger(function test() { console.log('test');});
let circularObj = {};
circularObj.circularRef = circularObj;
myLogger(circularObj);

// Still use the original console.log if needed
console.log('This is a regular console log.');



// More advanced usage: conditionally enable logging
function createConditionalLogProxy(enabled = true, prefix = '') {
  return enabled ? createLogProxy(prefix) : () => {}; // Return a no-op function if disabled
}

const debugLogger = createConditionalLogProxy(true, '[DEBUG]');
debugLogger('Debug information'); // This will log

const disabledLogger = createConditionalLogProxy(false);
disabledLogger('This will not log');


Key improvements in this version:

  • Timestamp: Adds a timestamp to each log entry.
  • Handles various data types: Correctly logs objects (including circular references), functions, and primitive types. Uses JSON.stringify for pretty-printing objects.
  • Prefix option: Allows adding a custom prefix to log messages.
  • Conditional Logging: Provides a way to easily enable/disable the proxy using createConditionalLogProxy. This is useful for debug logging that you might want to turn off in production.
  • No-op function when disabled: When disabled, the conditional proxy returns a no-op function, which is more efficient than checking a flag on every call.

This improved version provides more flexibility and better readability for your logs. It addresses potential issues with circular objects and provides a more robust and practical solution for everyday development.

posted @ 2024-12-10 09:44  王铁柱6  阅读(28)  评论(0)    收藏  举报