NuGet npm Samples

Logging to elmah.io from JavaScript

elmah.io doesn't only support server-side .NET logging. We also log JavaScript errors happening on your website. Logging client-side errors require nothing more than installing the elmahio.js script on your website.

Organizations created end 2023 and forward will have an API key named JavaScript automatically generated. Remember to either use this or generate a new API key with messages_write permission only. This makes it easy to revoke the API key if someone starts sending messages to your log with your key.

elmahio.js supports all modern browsers like Chrome, Edge, Firefox, and Safari. Internet Explorer 10 and 11 are supported too, but because of internal dependencies on the stacktrace-gps library, nothing older than IE10 is supported.

If you want to see elmahio.js in action before installing it on your site, feel free to play on the Playground.

Installation

Pick an installation method of your choice:

Download the latest release as a zip: https://github.com/elmahio/elmah.io.javascript/releases

Unpack and copy elmahio.min.js to the Scripts folder or whatever folder you use to store JavaScript files.

Reference elmahio.min.js just before the </body> tag (but before all other JavaScripts) in your shared _Layout.cshtml or all HTML files, depending on how you've structured your site:

<script src="~/Scripts/elmahio.min.js?apiKey=API_KEY&logId=LOG_ID" type="text/javascript"></script>

Reference elmahio.min.js just before the </body> tag (but before all other JavaScripts) in your shared _Layout.cshtml or all HTML files, depending on how you've structured your site:

<script src="https://cdn.jsdelivr.net/gh/elmahio/elmah.io.javascript@latest/dist/elmahio.min.js?apiKey=API_KEY&logId=LOG_ID" type="text/javascript"></script>

Install the elmah.io.javascript npm package:

npm install elmah.io.javascript

Reference elmahio.min.js just before the </body> tag (but before all other JavaScripts) in your shared _Layout.cshtml or all HTML files, depending on how you've structured your site:

<script src="~/node_modules/elmah.io.javascript/dist/elmahio.min.js?apiKey=API_KEY&logId=LOG_ID" type="text/javascript"></script>

Since Bower is no longer maintained, installing elmah.io.javascript through Bower, is supported using bower-npm-resolver. Install the resolver:

npm install bower-npm-resolver --save

Add the resolver in your .bowerrc file:

{
  "resolvers": [
    "bower-npm-resolver"
  ]
}

Install the elmah.io.javascript npm package:

bower install npm:elmah.io.javascript --save

Reference elmahio.min.js just before the </body> tag (but before all other JavaScripts) in your shared _Layout.cshtml or all HTML files, depending on how you've structured your site:

<script src="~/bower_components/elmah.io.javascript/dist/elmahio.min.js?apiKey=API_KEY&logId=LOG_ID" type="text/javascript"></script>

Add the elmah.io.javascript library in your libman.json file:

{
  // ...
  "libraries": [
    // ...
    {
      "provider": "filesystem",
      "library": "https://raw.githubusercontent.com/elmahio/elmah.io.javascript/3.7.1/dist/elmahio.min.js",
      "destination": "wwwroot/lib/elmahio"
    }
  ]
}

or using the LibMan CLI:

libman install https://raw.githubusercontent.com/elmahio/elmah.io.javascript/3.7.1/dist/elmahio.min.js --provider filesystem --destination wwwroot\lib\elmahio

Reference elmahio.min.js just before the </body> tag (but before all other JavaScripts) in your shared _Layout.cshtml or all HTML files, depending on how you've structured your site:

<script src="~/lib/elmahio/dist/elmahio.min.js?apiKey=API_KEY&logId=LOG_ID" type="text/javascript"></script>

NuGet is not a good distribution channel for JavaScript libraries so this package has been deprecated. The elmah.io.javascript package installs the JavaScript file in the /Scripts/ folder. This no longer works with modern web frameworks like ASP.NET Core. We recommend installing the JavaScript through one of the other options instead.

Install the elmah.io.javascript NuGet package:

Install-Package elmah.io.javascript
dotnet add package elmah.io.javascript
<PackageReference Include="elmah.io.javascript" Version="4.*" />
paket add elmah.io.javascript

Reference elmahio.min.js just before the </body> tag (but before all other JavaScripts) in your shared _Layout.cshtml or all HTML files, depending on how you've structured your site:

<script src="~/Scripts/elmahio.min.js?apiKey=API_KEY&logId=LOG_ID" type="text/javascript"></script>

If not already configured, follow the guide installing elmah.io in ASP.NET Core.

Install the Elmah.Io.AspNetCore.TagHelpers NuGet package:

Install-Package Elmah.Io.AspNetCore.TagHelpers
dotnet add package Elmah.Io.AspNetCore.TagHelpers
<PackageReference Include="Elmah.Io.AspNetCore.TagHelpers" Version="5.*" />
paket add Elmah.Io.AspNetCore.TagHelpers

Copy and paste the following line to the top of the _Layout.cshtml file:

@addTagHelper *, Elmah.Io.AspNetCore.TagHelpers

In the bottom of the file (but before referencing other JavaScript files), add the following tag helper:

<elmah-io/>

If you want to log JavaScript errors from production only, make sure to move the elmah-io element inside the tag <environment exclude="Development">.

elmah.io automatically pulls your API key and log ID from the options specified as part of the installation for logging serverside errors from ASP.NET Core. If you haven't installed that code already, include the following lines in the Program.cs file:

builder.Services.AddElmahIo(options =>
{
    options.ApiKey = "API_KEY";
    options.LogId = new Guid("LOG_ID");
});

That's it. All uncaught errors on your website, are now logged to elmah.io.

Options

If you prefer configuring in code (or need to access the options for something else), API key and log ID can be configured by referencing the elmahio.min.js script without parameters:

<script src="~/scripts/elmahio.min.js" type="text/javascript"></script>

Then initialize the logger in JavaScript:

new Elmahio({
    apiKey: 'API_KEY',
    logId: 'LOG_ID'
});

Application name

The application property on elmah.io can be set on all log messages by setting the application option:

new Elmahio({
    apiKey: 'API_KEY',
    logId: 'LOG_ID',
    application: 'My application name'
});

Debug output

For debug purposes, debug output from the logger to the console can be enabled using the debug option:

new Elmahio({
    apiKey: 'API_KEY',
    logId: 'LOG_ID',
    debug: true
});

Message filtering

Log messages can be filtered, by adding a filter handler in options:

new Elmahio({
    // ...
    filter: function(msg) {
        return msg.severity === 'Verbose';
    }
});

In the example, all log messages with a severity of Verbose, are not logged to elmah.io.

Events

Enriching log messages

Log messages can be enriched by subscribing to the message event:

new Elmahio({
    // ...
}).on('message', function(msg) {
    if (!msg.data) msg.data = [];
    msg.data.push({key: 'MyCustomKey', value: 'MyCustomValue'});
});

In the example, all log messages are enriched with a data variable with the key MyCustomKey and value MyCustomValue.

Handling errors

To react to errors happening in elmah.io.javascript, subscribe to the error event:

new Elmahio({
    // ...
}).on('error', function(status, text) {
    console.log('An error happened in elmah.io.javascript', status, text);
});

In the example, all errors are written to the console.

Breadcrumbs can be used to decorate errors with events or actions happening just before logging the error. Breadcrumbs can be added manually:

logger.addBreadcrumb('User clicked button x', 'Information', 'click');

You would want to enrich your code with a range of different breadcrumbs depending on important user actions in your application.

As default, a maximum of 10 breadcrumbs are stored in memory at all times. The list acts as first in first out, where adding a new breadcrumb to a full list will automatically remove the oldest breadcrumb in the list. The allowed number of breadcrumbs in the list can be changed using the breadcrumbsNumber option:

var logger = new Elmahio({
    // ...
    breadcrumbsNumber: 15
});

This will store a maximum of 15 breadcrumbs. Currently, we allow 25 as the highest possible value.

elmah.io.javascript can also be configured to automatically generate breadcrumbs from important actions like click events and xhr:

var logger = new Elmahio({
    // ...
    breadcrumbs: true
});

We are planning to enable automatic breadcrumbs in the future but for now, it's an opt-in feature. Automatic breadcrumbs will be included in the same list as manually added breadcrumbs why the breadcrumbsNumber option is still valid.

Logging manually

You may want to log errors manually or even log information messages from JavaScript. To do so, Elmahio is a logging framework too:

var logger = new Elmahio({
    apiKey: 'API_KEY',
    logId: 'LOG_ID'
});

logger.verbose('This is verbose');
logger.verbose('This is verbose', new Error('A JavaScript error object'));

logger.debug('This is debug');
logger.debug('This is debug', new Error('A JavaScript error object'));

logger.information('This is information');
logger.information('This is information', new Error('A JavaScript error object'));

logger.warning('This is warning');
logger.warning('This is warning', new Error('A JavaScript error object'));

logger.error('This is error');
logger.error('This is error', new Error('A JavaScript error object'));

logger.fatal('This is fatal');
logger.fatal('This is fatal', new Error('A JavaScript error object'));

logger.log({
  title: 'This is a custom log message',
  type: 'Of some type',
  severity: 'Error'
});

var msg = logger.message(); // Get a prefilled message
msg.title = "This is a custom log message";
logger.log(msg);

var msg = logger.message(new Error('A JavaScript error object')); // Get a prefilled message including error details
// Set custom variables. If not needed, simply use logger.error(...) instead.
logger.log(msg);

The Error object used, should be a JavaScript Error object.

As for the log-function, check out message reference.

Manual logging only works when initializing the elmah.io logger from code.

Logging from console

If you don't like to share the Elmahio logger or you want to hook elmah.io logging up to existing code, you can capture log messages from console. To do so, set the captureConsoleMinimumLevel option:

var log = new Elmahio({
  apiKey: 'API_KEY',
  logId: 'LOG_ID',
  captureConsoleMinimumLevel: 'error'
});

console.error('This is an %s message.', 'error');

captureConsoleMinimumLevel can be set to one of the following values:

  • none: will disable logging from console (default).
  • debug: will capture logging from console.debug, console.info, console.warn, console.error.
  • info: will capture logging from console.info, console.warn, console.error.
  • warn: will capture logging from console.warn, console.error.
  • error: will capture logging from console.error.

Capturing the console only works when initializing the elmah.io logger from code. Also, console.log is not captured.

IntelliSense

If installing through npm or similar, Visual Studio should pick up the TypeScript mappings from the elmah.io.javascript package. If not, add the following line at the top of the JavaScript file where you want elmah.io.javascript IntelliSense:

/// <reference path="/path/to/elmahio.d.ts" />

Message reference

This is an example of the elmah.io.javascript Message object that is used in various callbacks, etc.:

{
  title: 'this.remove is not a function',
  detail: 'TypeError: this.remove is not a function\n  at (undefined:12:14)',
  source: 'index.js',
  severity: 'Error',
  type: 'TypeError',
  url: '/current/page',
  method: 'GET',
  application: 'MyApp',
  hostname: 'WOPR',
  statusCode: 400,
  user: 'DavidLightman',
  version: '1.0.0',
  cookies: [
    { key: '_ga', value: 'GA1.3.1580453215.1783132008' }
  ],
  queryString: [
    { key: 'id', value: '42' }
  ],
  data: [
    { key: 'User-Language', value: 'en-US' },
    { key: 'Color-Depth', value: '24' }
  ],
  serverVariables: [
    { key: 'User-Agent', value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' }
  ],
  breadcrumbs: [
    { severity: 'Information', event: 'click', message: 'A user clicked' }
  ]
}

For a complete definition, check out the Message interface in the elmah.io.javascript TypeScript mappings.


This article was brought to you by the elmah.io team. elmah.io is the best error management system for .NET web applications. We monitor your website, alert you when errors start happening, and help you fix errors fast.

See how we can help you monitor your website for crashes Monitor your website