Instrumenting an Express application with Logfire is straightforward. You can use the logfire package to set up logging and monitoring for your Express routes.
importexpress,type{Express}from'express';constPORT:number=parseInt(process.env.PORT||'8080');constapp:Express=express();functiongetRandomNumber(min:number,max:number){returnMath.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:
npminstalllogfiredotenv
Add your token to the .env file:
.env
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:
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: