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, requires nothing more than installing the elmahio.js
script on your website.
Remember to disable access to the v2 API on your log and generate a new API key with
messages_write
permission only. Without these changes, everyone will be able to browse your logs (you don't want that!).
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=YOUR-API-KEY&logId=YOUR-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@3.0.0/dist/elmahio.min.js?apiKey=YOUR-API-KEY&logId=YOUR-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=YOUR-API-KEY&logId=YOUR-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=YOUR-API-KEY&logId=YOUR-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.0.0/dist/elmahio.min.js",
"destination": "wwwroot/lib/elmahio"
}
]
}
or using the LibMan CLI:
libman install https://raw.githubusercontent.com/elmahio/elmah.io.javascript/3.0.0/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=YOUR-API-KEY&logId=YOUR-LOG-ID" type="text/javascript"></script>
Install the elmah.io.javascript
NuGet package:
Install-Package 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=YOUR-API-KEY&logId=YOUR-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
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.
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 with parameters:
<script src="~/scripts/elmahio.min.js" type="text/javascript"></script>
Then initialize the logger in JavaScript:
new Elmahio({
apiKey: 'YOUR-API-KEY',
logId: 'YOUR-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: 'YOUR-API-KEY',
logId: 'YOUR-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: 'YOUR-API-KEY',
logId: 'YOUR-LOG-ID',
debug: true
});
Message filtering
Log messages can be filtered, by adding an 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 they key MyCustomKey
and value MyCustomValue
.
Handling errors
To react on 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.
Logging manually
You may want to log errors manually or even log information messages from JavaScript. To do so, Elmahio
is actually a logging framework too:
var logger = new Elmahio({
apiKey: 'YOUR-API-KEY',
logId: 'YOUR-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'
});
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.
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 in the top of the JavaScript file where you wan't elmah.io.javascript IntelliSense:
/// <reference path="/path/to/elmahio.d.ts" />
Angular
elmah.io.javascript
works great with Angular applications too. To log all errors happening in your Angular app, install elmah.io.javascript
through npm as described above. Then add elmahio.min.js
to the scripts
section in the .angular-cli.json
file (angular.json
in Angular 6):
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
...
"apps": [
{
...
"scripts": [
"../node_modules/elmah.io.javascript/dist/elmahio.min.js"
],
...
}
],
...
}
In the app.module.ts
file, add a new ErrorHandler
and add it to the providers
section:
import { NgModule, ErrorHandler } from '@angular/core';
...
class ElmahIoErrorHandler implements ErrorHandler {
logger: any;
constructor() {
this.logger = new Elmahio({
apiKey: 'API_KEY',
logId: 'LOG_ID',
});
}
handleError(error) {
if (error && error.message) {
this.logger.error(error.message, error);
} else {
this.logger.error('Error in application', error);
}
}
}
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [{ provide: ErrorHandler, useClass: ElmahIoErrorHandler }],
...
})
All errors are shipped to the handleError
-function by Angular and logged to elmah.io. Check out the Elmah.Io.JavaScript.Angular sample for some real working code.
React
To log all errors from a React application, install the elmah.io.javascript
npm package as described above. Then modify the App.js
file:
...
import Elmahio from '../node_modules/elmah.io.javascript/dist/elmahio';
export default class App extends Component {
...
constructor() {
super();
var log = new Elmahio({
apiKey: 'API_KEY',
logId: 'LOG_ID'
});
}
...
}
When initializing your React app, elmah.io is configured and all errors happening in the application are logged.
Message reference
This is an example of the elmah.io.javascript Message
object that is used in various callbacks, etc.:
{
title: 'The title of the message',
detail: 'The error stack',
source: 'The source of the error (typically a filename)',
severity: 'Error',
type: 'The type of the error',
url: 'http://url.of/current/page',
application: 'Application name set through options',
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'}
]
}
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