Product
Introducing Ruby Support in Socket
Socket is launching Ruby support for all users. Enhance your Rails projects with AI-powered security scans for vulnerabilities and supply chain threats. Now in Beta!
@datadog/browser-logs
Advanced tools
Send logs to Datadog from web browsers or other Javascript clients with the browser logs SDK.
@datadog/browser-logs is an npm package that allows you to collect and monitor logs from your web applications in real-time. It integrates with Datadog's logging service to provide comprehensive insights into your application's performance, errors, and user interactions.
Basic Logging
This feature allows you to initialize the Datadog logging client and send basic log messages. The `init` method configures the client with your Datadog client token and other settings, while the `logger.info` method sends an informational log message.
const { datadogLogs } = require('@datadog/browser-logs');
datadogLogs.init({
clientToken: 'YOUR_CLIENT_TOKEN',
site: 'datadoghq.com',
forwardErrorsToLogs: true,
sampleRate: 100,
});
datadogLogs.logger.info('This is an info log');
Error Logging
This feature allows you to log errors that occur in your application. By catching exceptions and using the `logger.error` method, you can send detailed error logs to Datadog.
try {
throw new Error('Something went wrong');
} catch (error) {
datadogLogs.logger.error('An error occurred', { error });
}
Custom Attributes
This feature allows you to add custom attributes to your log messages. By passing an object with additional data to the logging methods, you can enrich your logs with context-specific information.
datadogLogs.logger.info('User action', { userId: '12345', action: 'click' });
LogRocket is a front-end logging and session replay tool that helps you understand issues affecting your users. It provides similar logging capabilities as @datadog/browser-logs but also includes session replay, which allows you to see exactly what the user did leading up to an issue.
Loggly is a cloud-based log management service. The `loggly-jslogger` package allows you to send logs from your web applications to Loggly. It provides similar logging capabilities as @datadog/browser-logs but integrates with Loggly's log management and analysis platform.
Send logs to Datadog from web browsers or other Javascript clients with the browser logs SDK.
With the browser logs SDK, you can send logs directly to Datadog from JS clients and leverage the following features:
context
and extra custom attributes to each log sent.Datadog client token: For security reasons, API keys cannot be used to configure the browser logs SDK, because they would be exposed client-side in the JavaScript code. To collect logs from web browsers, a client token must be used. See the client token documentation for more details.
Datadog browser logs SDK: Configure the SDK through NPM or use the CDN async or CDN sync code snippets in the head tag.
Supported browsers: The browser logs SDK supports all modern desktop and mobile browsers including IE11. See the browser support table.
Installation method | Use case |
---|---|
npm (node package manager) | This method is recommended for modern web applications. The browser logs SDK gets packaged with the rest of your front-end javascript code. It has no impact on page load performance. However, the SDK might miss errors, resources and user actions triggered before the SDK is initialized. Note: it is recommended to use a matching version with RUM SDK if used. |
CDN async | This method is recommended for web applications with performance targets. The browser logs SDK is loaded from our CDN asynchronously: this method ensures the SDK download does not impact page load performance. However, the SDK might miss errors, resources and user actions triggered before the SDK is initialized. |
CDN sync | This method is recommended for collecting all RUM events. The browser logs SDK is loaded from our CDN synchronously: this method ensures the SDK is loaded first and collects all errors, resources and user actions. This method might impact page load performance. |
After adding @datadog/browser-logs
to your package.json
file, initialize it with:
import { datadogLogs } from '@datadog/browser-logs'
datadogLogs.init({
clientToken: '<DATADOG_CLIENT_TOKEN>',
site: '<DATADOG_SITE>',
forwardErrorsToLogs: true,
sampleRate: 100,
})
Load and configure the SDK in the head section of your pages.
<html>
<head>
<title>Example to send logs to Datadog</title>
<script>
(function(h,o,u,n,d) {
h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
d=o.createElement(u);d.async=1;d.src=n
n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
})(window,document,'script','https://www.datadoghq-browser-agent.com/datadog-logs-v4.js','DD_LOGS')
DD_LOGS.onReady(function() {
DD_LOGS.init({
clientToken: 'XXX',
site: 'datadoghq.com',
forwardErrorsToLogs: true,
sampleRate: 100,
})
})
</script>
</head>
</html>
Note: Early API calls must be wrapped in the DD_LOGS.onReady()
callback. This ensures the code only gets executed once the SDK is properly loaded.
To receive all logs and errors, load and configure the SDK at the beginning of the head section for your pages.
<html>
<head>
<title>Example to send logs to Datadog</title>
<script type="text/javascript" src="https://www.datadoghq-browser-agent.com/datadog-logs-v4.js"></script>
<script>
window.DD_LOGS &&
DD_LOGS.init({
clientToken: '<CLIENT_TOKEN>',
site: '<DATADOG_SITE>',
forwardErrorsToLogs: true,
sampleRate: 100,
})
</script>
</head>
</html>
Note: The window.DD_LOGS
check is used to prevent issues if a loading failure occurs with the SDK.
Types are compatible with TypeScript >= 3.8.2. For earlier versions, import JS sources and use global variables to avoid any compilation issues:
import '@datadog/browser-logs/bundle/datadog-logs'
window.DD_LOGS.init({
clientToken: '<CLIENT_TOKEN>',
site: '<DATADOG_SITE>',
forwardErrorsToLogs: true,
sampleRate: 100,
})
The following parameters are available to configure the Datadog browser logs SDK to send logs to Datadog:
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
clientToken | String | Yes | A Datadog client token. | |
site | String | Yes | datadoghq.com | The Datadog site of your organization. US: datadoghq.com , EU: datadoghq.eu |
service | String | No | The service name for your application. It should follow the tag syntax requirements. | |
env | String | No | The applicationās environment, for example: prod, pre-prod, staging, etc. It should follow the tag syntax requirements. | |
version | String | No | The applicationās version, for example: 1.2.3, 6c44da20, 2020.02.13, etc. It should follow the tag syntax requirements. | |
forwardErrorsToLogs | Boolean | No | true | Set to false to stop forwarding console.error logs, uncaught exceptions and network errors to Datadog. |
forwardConsoleLogs | "all" or an Array of "log" "debug" "info" "warn" "error" | No | [] | Forward logs from console.* to Datadog. Use "all" to forward everything or an array of console API names to forward only a subset. |
forwardReports | "all" or an Array of "intervention" "deprecation" "csp_violation" | No | [] | Forward reports from the Reporting API to Datadog. Use "all" to forward everything or an array of report types to forward only a subset. |
sampleRate | Number | No | 100 | The percentage of sessions to track: 100 for all, 0 for none. Only tracked sessions send logs. |
silentMultipleInit | Boolean | No | Prevent logging errors while having multiple init. | |
proxyUrl | String | No | Optional proxy URL (ex: https://www.proxy.com/path), see the full proxy setup guide for more information. | |
telemetrySampleRate | Number | No | 20 | Telemetry data (error, debug logs) about SDK execution is sent to Datadog in order to detect and solve potential issues. Set this option to 0 to opt out from telemetry collection. |
Options that must have a matching configuration when using the RUM
SDK:
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
trackSessionAcrossSubdomains | Boolean | No | false | Preserve the session across subdomains for the same site. |
useSecureSessionCookie | Boolean | No | false | Use a secure session cookie. This disables logs sent on insecure (non-HTTPS) connections. |
useCrossSiteSessionCookie | Boolean | No | false | Use a secure cross-site session cookie. This allows the logs SDK to run when the site is loaded from another one (iframe). Implies useSecureSessionCookie . |
After the Datadog browser logs SDK is initialized, send a custom log entry directly to Datadog with the API:
logger.debug | info | warn | error (message: string, messageContext = Context)
import { datadogLogs } from '@datadog/browser-logs'
datadogLogs.logger.info('Button clicked', { name: 'buttonName', id: 123 })
DD_LOGS.onReady(function () {
DD_LOGS.logger.info('Button clicked', { name: 'buttonName', id: 123 })
})
Note: Early API calls must be wrapped in the DD_LOGS.onReady()
callback. This ensures the code only gets executed once the SDK is properly loaded.
window.DD_LOGS && DD_LOGS.logger.info('Button clicked', { name: 'buttonName', id: 123 })
Note: The window.DD_LOGS
check is used to prevent issues if a loading failure occurs with the SDK.
The results are the same when using NPM, CDN async or CDN sync:
{
"status": "info",
"session_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"name": "buttonName",
"id": 123,
"message": "Button clicked",
"date": 1234567890000,
"origin": "logger",
"http": {
"useragent": "Mozilla/5.0 ...",
},
"view": {
"url": "https://...",
"referrer": "https://...",
},
"network": {
"client": {
"geoip": {...}
"ip": "xxx.xxx.xxx.xxx"
}
}
}
The Logs SDK adds the following information by default (more fields can be added if the RUM SDK is present):
date
view.url
view.referrer
session_id
(only if a session is used)The Datadog backend adds more fields, like:
http.useragent
network.client.ip
After the Datadog browser logs SDK is initialized, send a custom log entry to Datadog with the API using the status as a parameter:
log (message: string, messageContext: Context, status? = 'debug' | 'info' | 'warn' | 'error')
For NPM, use:
import { datadogLogs } from '@datadog/browser-logs';
datadogLogs.logger.log(<MESSAGE>,<JSON_ATTRIBUTES>,<STATUS>);
For CDN async, use:
DD_LOGS.onReady(function() {
DD_LOGS.logger.log(<MESSAGE>,<JSON_ATTRIBUTES>,<STATUS>);
})
Note: Early API calls must be wrapped in the DD_LOGS.onReady()
callback. This ensures the code only gets executed once the SDK is properly loaded.
For CDN sync, use:
window.DD_LOGS && DD_LOGS.logger.log(<MESSAGE>,<JSON_ATTRIBUTES>,<STATUS>);
The placeholders in the examples above are described below:
Placeholder | Description |
---|---|
<MESSAGE> | The message of your log that is fully indexed by Datadog. |
<JSON_ATTRIBUTES> | A valid JSON object, which includes all attributes attached to the <MESSAGE> . |
<STATUS> | The status of your log; accepted status values are debug , info , warn , or error . |
If your Browser logs contain sensitive information that needs redacting, configure the Browser SDK to scrub sensitive sequences by using the beforeSend
callback when you initialize the Browser Log Collector.
The beforeSend
callback function gives you access to each log collected by the Browser SDK before it is sent to Datadog, and lets you update any property.
To redact email addresses from your web application URLs:
import { datadogLogs } from '@datadog/browser-logs'
datadogLogs.init({
...,
beforeSend: (log) => {
// remove email from view url
log.view.url = log.view.url.replace(/email=[^&]*/, "email=REDACTED")
},
...
});
DD_LOGS.onReady(function() {
DD_LOGS.init({
...,
beforeSend: (log) => {
// remove email from view url
log.view.url = log.view.url.replace(/email=[^&]*/, "email=REDACTED")
},
...
})
})
window.DD_LOGS &&
window.DD_LOGS.init({
...,
beforeSend: (log) => {
// remove email from view url
log.view.url = log.view.url.replace(/email=[^&]*/, "email=REDACTED")
},
...
});
The following properties are automatically collected by the SDK and could contain sensitive data:
Attribute | Type | Description |
---|---|---|
view.url | String | The URL of the active web page. |
view.referrer | String | The URL of the previous web page from which a link to the currently requested page was followed. |
message | String | The content of the log. |
error.stack | String | The stack trace or complementary information about the error. |
http.url | String | The HTTP URL. |
The beforeSend
callback function allows you to also discard a log before it is sent to Datadog.
To discard network errors if their status is 404:
import { datadogLogs } from '@datadog/browser-logs'
datadogLogs.init({
...,
beforeSend: (log) => {
// discard 404 network errors
if (log.http && log.http.status_code === 404) {
return false
}
},
...
});
DD_LOGS.onReady(function() {
DD_LOGS.init({
...,
beforeSend: (log) => {
// discard 404 network errors
if (log.http && log.http.status_code === 404) {
return false
}
},
...
})
})
window.DD_LOGS &&
window.DD_LOGS.init({
...,
beforeSend: (log) => {
// discard 404 network errors
if (log.http && log.http.status_code === 404) {
return false
}
},
...
});
The Datadog browser logs SDK contains a default logger, but it is possible to define different loggers.
After the Datadog browser logs SDK is initialized, use the API createLogger
to define a new logger:
createLogger (name: string, conf?: {
level?: 'debug' | 'info' | 'warn' | 'error',
handler?: 'http' | 'console' | 'silent',
context?: Context
})
Note: These parameters can be set with the setLevel, setHandler, and setContext APIs.
After the creation of a logger, access it in any part of your JavaScript code with the API:
getLogger(name: string)
For example, assume there is a signupLogger
, defined with all the other loggers:
import { datadogLogs } from '@datadog/browser-logs'
datadogLogs.createLogger('signupLogger', 'info', 'http', { env: 'staging' })
It can now be used in a different part of the code with:
import { datadogLogs } from '@datadog/browser-logs'
const signupLogger = datadogLogs.getLogger('signupLogger')
signupLogger.info('Test sign up completed')
For example, assume there is a signupLogger
, defined with all the other loggers:
DD_LOGS.onReady(function () {
const signupLogger = DD_LOGS.createLogger('signupLogger', 'info', 'http', { env: 'staging' })
})
It can now be used in a different part of the code with:
DD_LOGS.onReady(function () {
const signupLogger = DD_LOGS.getLogger('signupLogger')
signupLogger.info('Test sign up completed')
})
Note: Early API calls must be wrapped in the DD_LOGS.onReady()
callback. This ensures the code only gets executed once the SDK is properly loaded.
For example, assume there is a signupLogger
, defined with all the other loggers:
if (window.DD_LOGS) {
const signupLogger = DD_LOGS.createLogger('signupLogger', 'info', 'http', { env: 'staging' })
}
It can now be used in a different part of the code with:
if (window.DD_LOGS) {
const signupLogger = DD_LOGS.getLogger('signupLogger')
signupLogger.info('Test sign up completed')
}
Note: The window.DD_LOGS
check is used to prevent issues if a loading failure occurs with the SDK.
After the Datadog browser logs SDK is initialized, it is possible to:
setLoggerGlobalContext (context: Context)
API.addLoggerGlobalContext (key: string, value: any)
API.getLoggerGlobalContext ()
API.For NPM, use:
import { datadogLogs } from '@datadog/browser-logs'
datadogLogs.setLoggerGlobalContext({ env: 'staging' })
datadogLogs.addLoggerGlobalContext('referrer', document.referrer)
const context = datadogLogs.getLoggerGlobalContext() // => {env: 'staging', referrer: ...}
For CDN async, use:
DD_LOGS.onReady(function () {
DD_LOGS.setLoggerGlobalContext({ env: 'staging' })
})
DD_LOGS.onReady(function () {
DD_LOGS.addLoggerGlobalContext('referrer', document.referrer)
})
DD_LOGS.onReady(function () {
var context = DD_LOGS.getLoggerGlobalContext() // => {env: 'staging', referrer: ...}
})
Note: Early API calls must be wrapped in the DD_LOGS.onReady()
callback. This ensures the code only gets executed once the SDK is properly loaded.
For CDN sync, use:
window.DD_LOGS && DD_LOGS.setLoggerGlobalContext({ env: 'staging' })
window.DD_LOGS && DD_LOGS.addLoggerGlobalContext('referrer', document.referrer)
var context = window.DD_LOGS && DD_LOGS.getLoggerGlobalContext() // => {env: 'staging', referrer: ...}
Note: The window.DD_LOGS
check is used to prevent issues if a loading failure occurs with the SDK.
After a logger is created, it is possible to:
setContext (context: Context)
API.addContext (key: string, value: any)
API:For NPM, use:
import { datadogLogs } from '@datadog/browser-logs'
datadogLogs.setContext("{'env': 'staging'}")
datadogLogs.addContext('referrer', document.referrer)
For CDN async, use:
DD_LOGS.onReady(function () {
DD_LOGS.setContext("{'env': 'staging'}")
})
DD_LOGS.onReady(function () {
DD_LOGS.addContext('referrer', document.referrer)
})
Note: Early API calls must be wrapped in the DD_LOGS.onReady()
callback. This ensures the code only gets executed once the SDK is properly loaded.
For CDN sync, use:
window.DD_LOGS && DD_LOGS.setContext("{'env': 'staging'}")
window.DD_LOGS && DD_LOGS.addContext('referrer', document.referrer)
Note: The window.DD_LOGS
check is used to prevent issues if a loading failure occurs with the SDK.
After the Datadog browser logs SDK is initialized, the minimal log level for your logger is set with the API:
setLevel (level?: 'debug' | 'info' | 'warn' | 'error')
Only logs with a status equal to or higher than the specified level are sent.
For NPM, use:
import { datadogLogs } from '@datadog/browser-logs'
datadogLogs.logger.setLevel('<LEVEL>')
For CDN async, use:
DD_LOGS.onReady(function () {
DD_LOGS.logger.setLevel('<LEVEL>')
})
Note: Early API calls must be wrapped in the DD_LOGS.onReady()
callback. This ensures the code only gets executed once the SDK is properly loaded.
For CDN sync, use:
window.DD_LOGS && DD_LOGS.logger.setLevel('<LEVEL>')
Note: The window.DD_LOGS
check is used to prevent issues if a loading failure occurs with the SDK.
By default, loggers created by the Datadog browser logs SDK are sending logs to Datadog. After the Datadog browser logs SDK is initialized, it is possible to configure the logger to:
console
and Datadog (http
)console
onlysilent
)setHandler (handler?: 'http' | 'console' | 'silent' | Array<handler>)
For NPM, use:
import { datadogLogs } from '@datadog/browser-logs'
datadogLogs.logger.setHandler('<HANDLER>')
datadogLogs.logger.setHandler(['<HANDLER1>', '<HANDLER2>'])
For CDN async, use:
DD_LOGS.onReady(function () {
DD_LOGS.logger.setHandler('<HANDLER>')
DD_LOGS.logger.setHandler(['<HANDLER1>', '<HANDLER2>'])
})
Note: Early API calls must be wrapped in the DD_LOGS.onReady()
callback. This ensures the code only gets executed once the SDK is properly loaded.
For CDN sync, use:
window.DD_LOGS && DD_LOGS.logger.setHandler('<HANDLER>')
window.DD_LOGS && DD_LOGS.logger.setHandler(['<HANDLER1>', '<HANDLER2>'])
Note: The window.DD_LOGS
check is used to prevent issues if a loading failure occurs with the SDK.
FAQs
Unknown package
The npm package @datadog/browser-logs receives a total of 881,960 weekly downloads. As such, @datadog/browser-logs popularity was classified as popular.
We found that @datadog/browser-logs demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Ā It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket is launching Ruby support for all users. Enhance your Rails projects with AI-powered security scans for vulnerabilities and supply chain threats. Now in Beta!
Product
Ensure open-source compliance with Socketās License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.