Already created a Cloudflare Logpush or Cloudflare HTTP requests source?
Removing it and creating a new source instead will provide you much better experience with much more suitable default configuration.
Collect logs from your Cloudflare Workers.
Create a new JavaScript • Node.js source in Better Stack Logs.
Removing it and creating a new source instead will provide you much better experience with much more suitable default configuration.
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 for edge JS runtime @logtail/edge
:
npm install --save @logtail/edge
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 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.
Instantiating the Logtail
class outside of fetch
handler method will allow different worker runs to share log queue.
Providing the ExecutionContext
instance (usually called ctx
) will ensure all logs will be sent to Better Stack. To ensure best results, always use the returned logger instance from Logtail::withExecutionContext()
method.
Want to learn more about log levels and middleware?
Continue to the Advanced usage of Logtail JavaScript client.
Please let us know at hello@betterstack.com.
We're happy to help! 🙏