如何使用所有路由配置 Azure AppInsights 来记录异常和控制台语句?
这是appInsights.js:
const appInsights = require('applicationinsights');
appInsights.setup(process.env.APPLICATIONINSIGHTS_CONNECTION_STRING)
.setAutoCollectConsole(true, true)
.setAutoCollectExceptions(true)
.start();
module.exports = appInsights
路线/index.js:
var express = require('express');
var router = express.Router();
const { appInsights } = require('../services/appInsights');
const { botService } = require('../services/bot');
router.get('/', function (req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/api/messages', async function (req, res, next) {
console.log("--inside /messages--")
try {
//call a method from bot.js
});
}
catch (error) {
console.error('Error in /messages:', error);
appInsights.defaultClient.trackException({ exception: error });
res.status(500).send('Internal Server Error');
}
目前,所有内容都在 App Insights 中记录为“跟踪”,即使我使用过,例外情况也不会单独显示
appInsights.defaultClient.trackException({ exception: error });
在index.js中,我也不确定如何在bot.js中使用它。我尝试在 Bot.js 中再次导入 appInsights,但这会导致日志重复。我熟悉 AWS,我只是创建了一个 lambda,默认情况下它有 Cloudwatch 日志,这是我第一次在 Azure 上工作。
我能够分别查看异常和跟踪中的日志。
catch 块中处理的异常显示在异常部分。
我已将此 try catch 块代码添加到index.js 文件中
try {
await someMethod();
res.status(200).send('Message processed successfully');
} catch (error) {
console.error('Error in /messages:', error);
appInsights.defaultClient.trackException({ exception: error });
res.status(500).send('Internal Server Error');
}
我的index.js文件:
const express = require('express');
const router = express.Router();
const appInsights = require('../services/appInsights');
const { someMethod } = require('../services/bot');
router.get('/', function (req, res, next) {
res.send('API running at: /api/names, /api/error, /api/dependency');
});
router.get('/api/names', (req, res, next) => {
res.json(['Tony', 'Lisa', 'Michael', 'Ginger', 'Food']);
});
router.get('/api/error', (req, res, next) => {
try {
throw new Error('This is a test error');
} catch (error) {
appInsights.defaultClient.trackException({ exception: error });
res.status(500).json({ error: 'Internal Server Error' });
}
});
router.post('/api/messages', async function (req, res, next) {
console.log("--inside /messages--");
try {
await someMethod();
res.status(200).send('Message processed successfully');
} catch (error) {
console.error('Error in /messages:', error);
appInsights.defaultClient.trackException({ exception: error });
res.status(500).send('Internal Server Error');
}
});
module.exports = router;
我的bot.js文件:
const appInsights = require('../services/appInsights');
async function someMethod() {
try {
console.log("Simulated successful process in bot service");
return "Success";
} catch (error) {
console.error('Error in bot service:', error);
appInsights.defaultClient.trackException({ exception: error });
throw error;
}
}
module.exports = {
someMethod
};
我在 appInsights.js 中添加了更多方法
我的appInsights.js文件
const appInsights = require('applicationinsights');
appInsights.setup("
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING")
.setAutoDependencyCorrelation(true)
.setAutoCollectRequests(true)
.setAutoCollectPerformance(true, true)
.setAutoCollectExceptions(true)
.setAutoCollectDependencies(true)
.setAutoCollectConsole(true, true)
.setUseDiskRetryCaching(true)
.setSendLiveMetrics(false)
.setDistributedTracingMode(appInsights.DistributedTracingModes.AI_AND_W3C)
.start();
module.exports = appInsights;
我的app.js文件:
const express = require('express');
const app = express();
const indexRouter = require('./routes/index');
const appInsights = require('./services/appInsights');
app.use(express.json());
app.use((req, res, next) => {
appInsights.defaultClient.trackRequest({ name: req.method + ' ' + req.url, url: req.url, time: new Date(), duration: 0, resultCode: res.statusCode, success: true });
next();
});
app.use('/', indexRouter);
app.use((err, req, res, next) => {
console.error('Unhandled error:', err);
appInsights.defaultClient.trackException({ exception: err });
res.status(500).send('Internal Server Error');
});
const port = process.env.PORT || 3000;
app.set('port', port);
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
现在,对于每条路线,我都有 App Insights 日志跟踪。