Express¶
Instrumenting an Express application with Logfire is straightforward. You can use the logfire
package to set up logging and monitoring for your Express routes.
Info
The @opentelemetry/instrumentation-express NPM package lists the following Express version requirements:
express
version >=4.0.0 <5
import express, type { Express } from 'express';
const PORT: number = parseInt(process.env.PORT || '8080');
const app: Express = express();
function getRandomNumber(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
app.get('/rolldice', (req, res) => {
res.send(getRandomNumber(1, 6).toString());
});
app.listen(PORT, () => {
console.log(`Listening for requests on http://localhost:${PORT}`);
});
To get started, install the logfire
and dotenv
NPM packages. This will allow you to keep your Logfire write token in a .env
file:
npm install logfire dotenv
Add your token to the .env
file:
LOGFIRE_TOKEN=your-write-token
Then, create an instrumentation.ts
file to set up the instrumentation. The
logfire
package includes a configure
function that simplifies the setup:
import * as logfire from "logfire";
import "dotenv/config";
logfire.configure();
The logfire.configure
call should happen before importing the actual Express module, so your NPM start script should look like this in package.json
. Note that we use npx ts-node
to run the TypeScript code directly:
"scripts": {
"start": "npx ts-node --require ./instrumentation.ts app.ts"
A working example can be found in the examples/express directory of the pydantic/logfire-js
repository.