Explore documentation
Better Stack Cloudflare Worker logging
Start logging in 5 minutes
Collect logs from your Cloudflare Workers.
Set up Cloudflare Worker
Either open your existing project with Wrangler CLI if you already have it set up, or initialize new "Hello World" Worker:
wrangler login
wrangler init better-stack-logging-example
cd better-stack-logging-example
Install Better Stack logging library
Install Better Stack logging library for edge JS runtime @logtail/edge
:
npm install --save @logtail/edge
Create and use instance of logger
Import and instantiate Logtail
class, add the execution context from the request, and use it for your application logs:
import { Logtail } from "@logtail/edge"
export const baseLogger = new Logtail("$SOURCE_TOKEN")
export interface Env {
// ...
}
export default {{
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const logger = baseLogger.withExecutionContext(ctx)
logger.debug("I am using Better Stack!")
logger.info("An interesting event occurred!")
// Logging structured data
logger.warn("Something is not quite right, better check on it.",{
user:{
username:"someuser",
email:"someuser@example.com"
},
additional_info:{
tried_accessing: "/url/of/error"
}
})
// Logging application errors
function callbackThatMightFail() {
throw new Error("Example error")
}
try {
callbackThatMightFail()
} catch (err) {
logger.error("Oops! An runtime ERROR occurred!", err)
}
return new Response('Hello world')
},
}
Deploy your worker
Deploy your worker using Wrangler CLI
wrangler deploy
Finally, open the worker's URL in your browser to run it.
You should see your logs in Better Stack -> Live tail.
Additional information
Instantiating the
Logtail
class outside offetch
handler method will allow different worker runs to share log queue.Providing the
ExecutionContext
instance (usually calledctx
) will ensure all logs will be sent to Better Stack. To ensure best results, always use the returned logger instance fromLogtail::withExecutionContext()
method.Want to learn more about log levels and middleware?
Continue to the Advanced usage of Logtail JavaScript client.
Need help?
Please let us know at hello@betterstack.com.
We're happy to help! 🙏