- Notifications
You must be signed in to change notification settings - Fork3
JavaScript and TypeScript SDK for Logfire
License
pydantic/logfire-js
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
From the team behindPydantic Validation,Pydantic Logfire is an observability platform built on the same belief as our open source library — that the most powerful tools can be easy to use.
What sets Logfire apart:
- Simple and Powerful: Logfire's dashboard is simple relative to the power it provides, ensuring your entire engineering team will actually use it.
- SQL: Query your data using standard SQL — all the control and (for many) nothing new to learn. Using SQL also means you can query your data with existing BI tools and database querying libraries.
- OpenTelemetry: Logfire is an opinionated wrapper around OpenTelemetry, allowing you to leverage existing tooling, infrastructure, and instrumentation for many common packages, and enabling support for virtually any language. We offer full support for all OpenTelemetry signals (traces, metrics, and logs).
Feel free to report issues and ask any questions about Logfire in this repository!
This repository contains the JavaScript SDK forlogfire
and its documentation; the server application for recording and displaying data is closed source.

Depending on your environment, you can integrate Logfire in several ways. Followthe specific instructions below:
Using Logfire from your Node.js script is as simple asgetting a write token,installing the package, calling configure, and using the provided API. Let'screate an empty project:
mkdir test-logfire-jscd test-logfire-jsnpm init -y es6# creates package.json with `type: module`npm install logfire
Then, create the followinghello.js
script in the directory:
import*aslogfirefrom"logfire";logfire.configure({token:"test-e2e-write-token",advanced:{baseUrl:"http://localhost:8000",},serviceName:"example-node-script",serviceVersion:"1.0.0",});logfire.info("Hello from Node.js",{"attribute-key":"attribute-value",},{tags:["example","example2"],});
Run the script withnode hello.js
, and you should see the span being logged inthe live view of your Logfire project.
First, install the@pydantic/logfire-cf-workers @pydantic/logfire-api
NPMpackages:
npm install @pydantic/logfire-cf-workers @pydantic/logfire-api
Next, addcompatibility_flags = [ "nodejs_compat" ]
to your wrangler.toml or"compatibility_flags": ["nodejs_compat"]
if you're usingwrangler.jsonc
.
Add yourLogfire write tokento your.dev.vars
file:
LOGFIRE_TOKEN=your-write-tokenLOGFIRE_ENVIRONMENT=development
TheLOGFIRE_ENVIRONMENT
variable is optional and can be used to specify the environment for the service.
For production deployment, check theCloudflare documentation for details on managing and deploying secrets.
One way to do this is through thenpx wrangler
command:
npx wrangler secret put LOGFIRE_TOKEN
Next, add the necessary instrumentation around your handler. ThetracerConfig
function will extract your write token from theenv
object and provide thenecessary configuration for the instrumentation:
import*aslogfirefrom"@pydantic/logfire-api";import{instrument}from"@pydantic/logfire-cf-workers";consthandler={asyncfetch():Promise<Response>{logfire.info("info span from inside the worker body");returnnewResponse("hello world!");},}satisfiesExportedHandler;exportdefaultinstrument(handler,{service:{name:'my-cloudflare-worker',namespace:'',version:'1.0.0',},});
A working example can be found in theexamples/cloudflare-worker
directory.
Note: if you're testing your worker with Vitest, you need to add the following additional configuration to yourvitest.config.mts
:
export default defineWorkersConfig({ test: { deps: { optimizer: { ssr: { enabled: true, include: ['@pydantic/logfire-cf-workers'], }, }, }, poolOptions: { workers: { // ... }, }, },});
Vercel provides a comprehensive OpenTelemetry integration through the@vercel/otel
package. After followingtheir integration instructions, add thefollowing environment variables to your project:
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://logfire-api.pydantic.dev/v1/tracesOTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://logfire-api.pydantic.dev/v1/metricsOTEL_EXPORTER_OTLP_HEADERS='Authorization=your-write-token'
This will point the instrumentation to Logfire.
Note
Vercel production deployments have a caching mechanism that might preventchanges from taking effect immediately or spans from being reported. If youare not seeing spans in Logfire, you canclear the data cache for your project.
Optionally, you can use the Logfire API package for creating manual spans.Install the@pydantic/logfire-api
NPM package and call the respective methodsfrom your server-side code:
import*aslogfirefrom"@pydantic/logfire-api";exportdefaultasyncfunctionHome(){returnlogfire.span("A warning span",{},{level:logfire.Level.Warning,},async(span)=>{logfire.info("Nested info span");return<div>Hello</div>;});}
A working example can be found in theexamples/nextjs
directory.
The@vercel/otel
package does not support client-side instrumentation, so few additional steps are necessary to send spans and/or instrument the client-side.For a working example, refer to theexamples/nextjs-client-side-instrumentation
directory, which instruments the client-sidefetch
calls.
For this example, we will instrument a simple Express app:
/*app.ts*/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}`);});
Next, install thelogfire
anddotenv
NPM packages to keep your Logfire writetoken in a.env
file:
npm install logfire dotenv
Add your token to the.env
file:
LOGFIRE_TOKEN=your-write-token
Then, create aninstrumentation.ts
file to set up the instrumentation. Thelogfire
package includes aconfigure
function that simplifies the setup:
// instrumentation.tsimport*aslogfirefrom"logfire";import"dotenv/config";logfire.configure();
Thelogfire.configure
call should happen before the actual express moduleimports, so your NPM start script should look like this (package.json
):
"scripts": {"start":"npx ts-node --require ./instrumentation.ts app.ts"},
Deno hasbuilt-in support for OpenTelemetry.The examples directory includes aHello world
example that configures DenoOTel export to Logfire through environment variables.
Optionally, you can use the Logfire API package for creating manual spans.Install the@pydantic/logfire-api
NPM package and call the respective methodsfrom your code.
Thelogfire.configure
function accepts a set of configuration options thatcontrol the behavior of the instrumentation. Alternatively, you canuse environment variablesto configure the instrumentation.
The@pydantic/logfire-api
exports several convenience wrappers around theOpenTelemetry span creation API. Thelogfire
package re-exports these.
The following methods create spans with their respective log levels (ordered byseverity):
logfire.trace
logfire.debug
logfire.info
logfire.notice
logfire.warn
logfire.error
logfire.fatal
Each method accepts a message, attributes, and optionally, options that let youspecify the span tags. The attribute values must be serializable to JSON.
functioninfo(message:string,attributes?:Record<string,unknown>,options?:LogOptions,):void;
In addition totrace
,debug
, the Logfire API exports areportError
function that accepts a message and a JavaScriptError
object. It will extract the necessary details from the error and create a span with theerror
level.
try{1/0}catch(error){logfire.reportError("An error occurred",error);}
SeeCONTRIBUTING.md for development instructions.
MIT
About
JavaScript and TypeScript SDK for Logfire
Resources
License
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.