Client-Side Logging

In the LogDNA Node.js library (version 3.0.1+), you can now use LogDNA’s Node.js library to log your client-side JavaScript applications to LogDNA. The library sends logs directly from your end users to LogDNA’s ingestion servers, letting you collect vital operational and debugging information without having to print logs to the console. The library offers a complete feature set including multiple log levels, customizable metadata, and the ability to add tags.

Adding Client-Side Logging to Your App

The LogDNA Node.js library supports Browserify and Webpack – utilities that automatically bundles JavaScript files along with any modules that they reference. You can use the require method to reference the LogDNA library from any JavaScript file, and Browserify will compile the library along with its required modules. You can then deploy the compiled file with your website as you would a normal JavaScript file.

With Browserify installed, follow the setup instructions on the Node.js agent page to initialize and configure the LogDNA agent. When declaring Logger.createLogger(), replace “API KEY HERE” with your LogDNA ingestion key. We recommend creating a new API key specifically for this use case.

const Logger = require('logdna');
const logger = Logger.createLogger('API KEY HERE', {
    hostname: 'client-device',
    app: 'my-client-side-app',
    index_meta: true
});

To avoid hard-coding your API key into your source code (which you should never do!), you can use a library such as envify to replace the API key string with an environment variable. Pass in your API key when calling Browserify, and envify will automatically insert it into the final bundle.

For example, the following code snippet replaces the hard-coded API key with the value stored in the LOGDNA_API_KEY environment variable:

const logger = Logger.createLogger(process.env.LOGDNA_API_KEY, {
    …
});

The following command calls Browserify and packages our source code file (“logdna.js”) into a bundle named “bundle.js”, replacing process.env.LOGDNA_API_KEY with our actual API key:

$ browserify logdna.js -t [ envify --LOGDNA_API_KEY <your actual API key> ] > bundle.js

Now, you can include the newly created “bundle.js” file in your web application:

<script src="bundle.js" type="application/javascript"></script>

To avoid CORS Issues

Before running the script, you will need to whitelist your domain in the LogDNA web app. Open the LogDNA web app and navigate to Settings > Organization > Whitelist Domains. Enter the domain(s) that you are deploying the script to. For example, if you are hosting a website at mydomain.com, you would add the domain as shown in the following screenshot. It may take a few minutes for your changes to take effect.