linux

JS日志记录哪些关键数据

小樊
40
2025-05-30 20:58:06
栏目: 编程语言

在JavaScript中,记录关键数据对于调试、监控和性能优化至关重要。以下是一些常见的关键数据类型,你可以在日志中记录它们:

1. 错误信息

try {
  // 代码块
} catch (error) {
  console.error('Error Type:', error.name);
  console.error('Error Message:', error.message);
  console.error('Stack Trace:', error.stack);
}

2. 请求和响应

fetch('https://api.example.com/data')
  .then(response => {
    console.log('Status Code:', response.status);
    return response.json();
  })
  .then(data => console.log('Data:', data))
  .catch(error => console.error('Fetch Error:', error));

3. 用户交互

document.getElementById('myButton').addEventListener('click', () => {
  console.log('Button Clicked at:', new Date());
});

4. 性能指标

console.time('Function Execution Time');
// 执行某个函数
console.timeEnd('Function Execution Time');

5. 应用状态

console.log('Current URL:', window.location.href);
console.log('User Logged In:', isLoggedIn);
console.log('Device Info:', navigator.userAgent);

6. 数据库操作

db.query('SELECT * FROM users', (error, results) => {
  if (error) {
    console.error('Database Query Error:', error);
  } else {
    console.log('Query Results:', results);
  }
});

7. 第三方库和API调用

axios.get('https://api.thirdparty.com/data')
  .then(response => console.log('Third Party API Response:', response.data))
  .catch(error => console.error('Third Party API Error:', error));

8. 日志级别

console.log('INFO: Operation completed successfully.');
console.warn('WARN: Potential issue detected.');
console.error('ERROR: Critical error occurred.');
console.debug('DEBUG: Detailed debugging information.');

注意事项

通过记录这些关键数据,你可以更好地理解应用的行为,快速定位和解决问题。

0
看了该问题的人还看了