UNPKG

10.9 kBMarkdownView Raw
1# Sumo Logic JavaScript Logging SDK
2
3The [Sumo Logic](http://www.sumologic.com) JavaScript Logging SDK library enables you to send custom log messages to an [HTTP Source](https://help.sumologic.com/Send_Data/Sources/02Sources_for_Hosted_Collectors/HTTP_Source) without installing a Collector on your server by using a CommonJS module (`sumoLogger.js`).
4
5You must have created an HTTP source in your Sumo Logic account to use this SDK. To create one, log into Sumo Logic, go to the Collectors page and either create a new Hosted Collector or add a new HTTP source to an existing Hosted Collector. Online help is available on that page with all the relevant details.
6
7*Basics:*
8
9All logs are sent as JSON objects by default. If you call `log()` with just a string, the string is included as a field called `msg`. If you call the function with a JSON object, each field in the object is included as a separate field. Fields called `sessionId`, `url`, and `timestamp` are sent in both cases.
10
11Messages are batched and sent at the configured interval/batch size; default for both is zero, meaning messages are sent to the server on each call. You can force any queued messages to be sent, typically during a shutdown or logout flow.
12
13| Module Deprecation Notice |
14| --- |
15| NOTE: Use of the `sumologic.logger.js` module is deprecated as of v2.0.0. It will be removed entirely in v3.0.0. Starting with v2.0.0 no updates will be made to this module. Please use the `sumoLogger.js` module instead. |
16
17### Table of Contents
18- [Sumo Logic JavaScript Logging SDK](#sumo-logic-javascript-logging-sdk)
19 - [Table of Contents](#table-of-contents)
20 - [Installation](#installation)
21 - [Usage](#usage)
22 - [Core functions](#core-functions)
23 - [Configuration](#configuration)
24 - [Per Message Options](#per-message-options)
25 - [Usage Examples](#usage-examples)
26 - [Security Note](#security-note)
27 - [Tests](#tests)
28 - [Issues](#issues)
29 - [Credits](#credits)
30 - [License](#license)
31
32## Installation
33
34**Prerequisites**
35
36You must have an HTTP source in your Sumo Logic account to use this SDK. To create one:
37* log into Sumo Logic,
38* go to the Manage Collection page, and,
39* **either** add a new HTTP source to a new or existing Hosted Collector **or** select an existing HTTP source.
40
41You’ll need the endpoint URL to configure the logger object. You can get it by clicking the `Show URL` link for the source on the Manage Collection page.
42
43If you don't have a Sumo Logic account yes, you can easily create one by going to https://www.sumologic.com and clicking the Free Trial button--no cost, just enter your email.
44
45You must also have Node.js/npm installed to use the SDK. [Node installation](https://docs.npmjs.com/getting-started/installing-node)
46
47Please review the Security Note at the end of this article before planning your implementation.
48
49**Using NPM:**
50```
51$ npm install --save sumo-logger
52```
53
54**From GitHub:**
55* Download or clone this repo.
56* Copy the files in the `src` folder into your app/website source.
57* Add `<script src="path/to/sumoLogger.js"></source>` to your pages or `import` or `require` the module in your app.
58* Add a `<script>` block with the desired log call to your pages, or use the function as needed in your app, as explained in [Usage](#user-content-usage).
59
60## Usage
61
62### Core functions
63
64* `log`: Set a log to be sent.
65* `flushLogs`: Force any pending logs to be sent immediately. This is mainly for use in a `logOut`/`window.onBeforeUnload` flow to ensure that any remaining queued messages are sent to Sumo Logic.
66* `startLogSending`: Start sending batched logs at the preconfigured interval
67* `stopLogSending`: Stop sending batched logs
68
69### Configuration
70
71Before sending any messages your page should set up the SumoLogger object. Of all the configurable attributes, only `endpoint` is required and all others are optional.
72
73*endpoint (Required)*
74
75To send your logs, the script must know which HTTP Source to use. Pass this value (which you can get from the Collectors page) in the `endpoint` parameter.
76
77*returnPromise (optional)*
78
79Default: TRUE. Causes `log()` to return a promise and ignore the `onSuccess` and `onError` handler options (if passed). ONLY works when logs are sent individually and not batched (`interval: 0`).
80
81*interval (optional)*
82
83A number of milliseconds. Messages will be batched and sent at the interval specified. Default value is zero, meaning messages are sent each time `log()` is called. If both `batchSize` and `interval` are configured sending will be triggered when the pending logs' aggregate message length is reached or when the specified interval is hit, and in either case the interval will be reset on send.
84
85*useIntervalOnly (optional)*
86
87Boolean. If enabled `batchSize` is ignored and only `interval` is used to trigger when the pending logs will be sent.
88
89*batchSize (optional)*
90
91An integer specifying total log length. This can be used by itself or in addition to `interval` but is ignored when `useIntervalOnly` is true. For higher volume applications, Sumo Logic recommends using between 100000 and 1000000 to optimize the tradeoff between network calls and load. If both `batchSize` and `interval` are configured sending will be triggered when the pending logs' aggregate message length is reached or when the specified interval is hit, and in either case the interval will be reset on send.
92
93*onSuccess (optional)*
94
95You can provide a function that is executed only when logs are successfully sent. The only information you can be sure of in the callback is that the call succeeded. There is no other response information.
96
97*onError (optional)*
98
99You can provide a function that is executed if an error occurs when the logs are sent.
100
101*graphite (optional)*
102
103Enables graphite metrics sending.
104
105*raw (optional)*
106
107Enables sending raw text logs exactly as they are passed to the logger.
108
109*clientUrl (optional)*
110
111You can provide a URL, in the Node version of this SDK only, which will be sent as the `url` field of the log line. In the vanilla JS version, the URL is detected from the browser's `window.location` value.
112
113*sessionKey (optional)*
114
115To identify specific user sessions, set a value for this field.
116
117*hostName (optional)*
118
119This value identifies the host from which the log is being sent.
120
121*sourceCategory (optional)*
122
123This value sets the Source Category for the logged message.
124
125*sourceName (optional)*
126
127This value sets the Source Name for the logged message.
128
129### Per Message Options
130
131All variants of the log call take an optional object parameter, which can include any of the following fields:
132
133*timestamp:*
134
135Defaults to `new Date()` called when processing the `log` call. Use this when the event being logged occurred at a different time than when the log was sent.
136
137*sessionKey:*
138
139Override a session key set in the `config` call.
140
141*url*
142
143Override client URL set in the `config` call. (Node version only)
144
145### Usage Examples
146
147**Full configuration:**
148
149```javascript
150 var opts = {
151 endpoint: "https://us2-events.sumologic.com/receiver/v1/http/222loremipsumetc32FG",
152 returnPromise: false,
153 interval: 20000, // Send messages in batches every 20 seconds
154 batchSize: 100000 // Or when total log length reaches 100k characters
155 sendErrors: true,
156 sessionKey: 'Abc32df34rfg54gui8j098dv13sq5re', // generate a GUID
157 sourceName: 'My Custom App',
158 sourceCategory: 'My Source Category',
159 hostName: 'My Host Name',
160 onSuccess: function() {
161 // ... handle success ....
162 },
163 onError: function() {
164 // ... handle error ....
165 },
166 graphite: true // Enable graphite metrics
167 };
168```
169
170***Logging***
171```javascript
172const SumoLogger = require('sumo-logger');
173const opts = {
174 endpoint: 'your HTTP Source endpoint',
175 clientUrl: 'http://yourDomain.com/path/to/page' // NODE version only,
176 // ... any other options ...
177};
178
179// Instantiate the SumoLogger
180const sumoLogger = new SumoLogger(opts);
181
182// Push a message to be logged
183sumoLogger.log('event message to log', {
184 sessionKey: 'your session key value',
185 url: 'https://youDomain.com/actual/page/served'
186}).then(() => /* handle positive response */)
187.catch(() => /* handle error response */);
188
189// Flush any logs, typically this line would be in your shutdown code
190sumoLogger.flushLogs();
191```
192
193***Metrics***
194```javascript
195const SumoLogger = require('sumo-logger');
196const opts = {
197 endpoint: 'your HTTP Source endpoint',
198 graphite: true // enable graphite metrics
199 // ... any other options ...
200};
201
202// Instantiate the SumoLogger
203const sumoLogger = new SumoLogger(opts);
204
205// Push a metric
206sumoLogger.log({
207 path: 'metric.path', // metric path as a dot separated string
208 value: 100 // value of the metric
209}).then(() => /* handle positive response */)
210.catch(() => /* handle error response */);
211```
212
213*Field Extraction Rules:* [fields in Sumo Logic](https://help.sumologic.com/Manage/Search-Optimization-Tools/Manage-Field-Extractions)
214
215## Security Note
216
217Sumo Logic is always concerned with security but in some instances we must balance risks with value of functionality. Using the vanilla JS version of this library is one such situation.
218
219Hitting an HTTP source endpoint from code running in a web browser exposes the endpoint URL to anyone inspecting the code or running your app with the browser console open to the network tab. There is no means to obfuscate or hide this. The risk is some malicious individual will send additional traffic to the endpoint, potentially using up your ingest or polluting your searches.
220
221If this is a concern for you, **we recommend using the the lib from a Node.js app running on your server** so your endpoint URL is never exposed.
222
223One method for minimizing the damage from some malicious users, should you choose to use this or other similar code in the browser, is adding an arbitrary string based on a regex to your log message and adding a processing rule to the HTTP source configuration that blocks incoming messages which lack a match for the regex.
224
225## Tests
226
227Tests are in the `test/` directory and can be run using the following command
228```
229$ npm run test
230```
231
232To generate a coverage report which is visible at `coverage/lcov-report/index.html`, run this command
233```
234$ npm run cover
235```
236
237## Issues
238
239Please file issues or feature requests on this Github repo.
240
241## Credits
242
243Thanks to [Clement Allen](https://github.com/clementallen) for his many contributions to this project.
244
245## TLS 1.2 Requirement
246
247Sumo Logic only accepts connections from clients using TLS version 1.2 or greater. To utilize the content of this repo, ensure that it's running in an execution environment that is configured to use TLS 1.2 or greater.
248
249## License
250
251Copyright 2017-2018, Sumo Logic, Inc. The Sumo Logic JavaScript Logging SDK is published under the Apache Software License, Version 2.0. Please visit http://www.apache.org/licenses/LICENSE-2.0.txt for details.