GithubHelp home page GithubHelp logo

nodejs's Introduction

Node.js library for logging to LogDNA

Build Status Known Vulnerabilities


Deprecation Notice

This package has been deprecated in favor of the @logdna/logger package. Please use @logdna/logger instead of the logdna package.


Install

$ npm install --save logdna

Setup

var Logger = require('logdna');
var options = {
    hostname: myHostname,
    ip: ipAddress,
    mac: macAddress,
    app: appName,
    env: envName
};

// Defaults to false, when true ensures meta object will be searchable
options.index_meta = true;

// Add tags in array or comma-separated string format:
options.tags = ['logging', 'nodejs', 'logdna'];
// or:
options.tags = 'logging,nodejs,logdna';

// Create multiple loggers with different options
var logger = Logger.createLogger(apikey, options);

Required

Optional

  • Hostname - (String) - max length 32 chars
  • MAC Address - (String)
  • IP Address - (String)
  • Max Length - (Boolean) - formatted as options.max_length
  • Index Meta - (Boolean) - formatted as options.index_meta
  • logdna_url - (String) - alternate ingest URL

Usage

After initial setup, logging is as easy as:

// Simplest use case
logger.log('My Sample Log Line');

// Add a custom level
logger.log('My Sample Log Line', 'MyCustomLevel');

// Include an App name with this specific log
logger.log('My Sample Log Line', { level: 'Warn', app: 'myAppName'});

// Pass an associated object along with a specific line as metadata...
var meta = {
    foo: 'bar',
    nested: {
      nest1: 'nested text'
    }
};

var opts = {
  level: 'warn',
  meta: meta
};

logger.log('My Sample Log Line', opts);

For more options, this module also offers:

// We support the following six levels
logger.info('My Sample Log Line');
logger.warn('My Sample Log Line');
logger.debug('My Sample Log Line');
logger.error('My Sample Log Line');
logger.fatal('My Sample Log Line');

// Functions above also accept additional options
logger.trace('My Sample Log Line', { app: 'myAppName'});

var opts = {
  level: 'trace',
  meta: {
    foo: 'bar',
    nested: {
      nest1: 'nested text'
    }
  }
};

// Functions above also pass any associated objects along as metadata
logger.trace('My Sample Log Line', opts);

// To add metadata to every log line created by the logger instance:
logger.addMetaProperty('fizz', 'buzz');

// To overwrite the default `fizz` metadata from the logger instance:
var opts = {
  meta: {
    fizz: 'not-buzz'
  }
};

logger.log('My Sample Log Line', opts);

You will see the outputs in your LogDNA dashboard.

API

createLogger(key, [options])


key

  • Required
  • Type: String
  • Values: YourIngestionKey

The LogDNA Ingestion Key associated with your account.

options

app
  • Optional
  • Type: String
  • Default: ''
  • Values: YourCustomApp
  • Max Length: 32

The default app passed along with every log sent through this instance.

hostname
  • Optional
  • Type: String
  • Default: ''
  • Values: YourCustomHostname
  • Max Length: 32

The default hostname passed along with every log sent through this instance.

env
  • Optional
  • Type: String
  • Default: ''
  • Values: YourCustomEnvironment
  • Max Length: 32

The default environment passed along with every log sent through this instance.

index_meta
  • Optional
  • Type: Boolean
  • Default: false

We allow meta objects to be passed with each line. By default these meta objects will be stringified and will not be searchable, but will be displayed for informational purposes.

If this option is turned to true then meta objects will be parsed and will be searchable up to three levels deep. Any fields deeper than three levels will be stringified and cannot be searched.

WARNING When this option is true, your metadata objects across all types of log messages MUST have consistent types or the metadata object may not be parsed properly!

cleanUpSIGTERM

WARNING Deprecated, you will have to opt-in and call cleanUpAll, where appropriate. AWS Lambda users have issues with listening on SIGTERM/SIGINT

cleanUpSIGINT

WARNING Deprecated, you will have to opt-in and call cleanUpAll, where appropriate. AWS Lambda users have issues with listening on SIGTERM/SIGINT

ip
  • Optional
  • Type: String
  • Default: ''
  • Values: 10.0.0.1

The default IP Address passed along with every log sent through this instance.

level
  • Optional
  • Type: String
  • Default: Info
  • Values: Debug, Trace, Info, Warn, Error, Fatal, YourCustomLevel
  • Max Length: 32

The default level passed along with every log sent through this instance.

mac
  • Optional
  • Type: String
  • Default: ''
  • Values: C0:FF:EE:C0:FF:EE

The default MAC Address passed along with every log sent through this instance.

max_length
  • Optional
  • Type: Boolean
  • Default: true

By default the line has a maximum length of 32000 chars, this can be turned off with the value false.

timeout
  • Optional
  • Type: Integer
  • Default: 180000
  • Max Value: 300000

The length of the timeout on the POST request that is sent to LogDNA.

with_credentials
  • Optional
  • Type: Boolean
  • Default: false

The withCredentials option passed to the request library. In order to make CORS requests this value is set to false by default.

log(line, [options])


line

  • Required
  • Type: String
  • Default: ''
  • Max Length: 32000

The line which will be sent to the LogDNA system.

options

Please note that if you are using variables for any of the below options, their values may change in between the line being logged and the batch of lines being flushed to our servers. If your variables change frequently, we highly recommend copying the value instead of referencing the variable directly.

level
  • Optional
  • Type: String
  • Default: Info
  • Values: Debug, Trace, Info, Warn, Error, Fatal, YourCustomLevel
  • Max Length: 32

The level passed along with this log line.

app
  • Optional
  • Type: String
  • Default: ''
  • Values: YourCustomApp
  • Max Length: 32

The app passed along with this log line.

env
  • Optional
  • Type: String
  • Default: ''
  • Values: YourCustomEnvironment
  • Max Length: 32

The environment passed along with this log line.

meta
  • Optional
  • Type: JSON
  • Default: null

A meta object that provides additional context about the log line that is passed.

index_meta
  • Optional
  • Type: Boolean
  • Default: false

We allow meta objects to be passed with each line. By default these meta objects will be stringified and will not be searchable, but will be displayed for informational purposes.

If this option is turned to true then meta objects will be parsed and will be searchable up to three levels deep. Any fields deeper than three levels will be stringified and cannot be searched.

WARNING When this option is true, your metadata objects across all types of log messages MUST have consistent types or the metadata object may not be parsed properly!

timestamp
  • Optional
  • Default: Date.now()

A timestamp in ms, must be within one day otherwise it will be dropped and Date.now() will be used in its place.

flushAll(callback)


A function that flushes all existing loggers that are instantiated by createLogger.

Returns the callback with an error as a first argument if one of the loggers failed to flush.

cleanUpAll()


A function that flushes all existing loggers that are instantiated by createLogger, and then removes references to them. Should only be called when you are finished logging.

Default Metadata

If you'd like to add metadata to each log line generated by the logger instance rather than adding metadata to each log line individually, use the following meta functions.

The key-value pair that you add will be automatically added to each log line's metadata. However, if you pass in any meta keys to an individual line instance using the options argument, those will overwrite any corresponding values that were set by the logger's default metadata.

addMetaProperty(key, value)


A function that adds key/value pair into the logger's default meta.

removeMetaProperty(key)


A function that removes the key and associated value from the logger's default meta.

Client Side

Browserify Support in version ^3.0.1

const Logger = require('logdna');
const logger = Logger.createLogger('API KEY HERE', {
    hostname:'ClientSideTest'
    , app: 'sequence'
    , index_meta: true
});

const date = new Date().toISOString();
const logme = (callback) => {
    for (var i = 0; i < 10; i++) {
        logger.log('Hello LogDNA Test ' + date, { meta: { sequence: i }});
    }
    return callback && callback();
};


setInterval(logme, 5000);

If the above snippet is saved as a file main.js. Then with browserify you can convert this to a bundle.js file.

browserify main.js -o bundle.js

The bundle.js file can be included like any other script.

<script src="bundle.js"></script>

When using NodeJS inside a browser, the domain needs to be whitelisted in your LogDNA organization settings

Bunyan Stream

For Bunyan Stream support please reference our logdna-bunyan module

Winston Transport

For Winston support please reference our logdna-winston module

AWS Lambda Support

AWS Lambda allows users to add logging statements to their Lambda Functions. You can choose to setup the logger as shown above, or you can override the console.log, console.error statements. AWS Lambda overrides the console.log, console.error, console.warn, and console.info functions as indicated here, within the scope of the handler (main) function. You can setup an override as follows:

'use strict';

const https = require('https');
const Logger = require('logdna');

const options = {
    env: 'env'
    , app: 'lambda-app'
    , hostname: 'lambda-test'
    , index_meta: true
};

var _log = console.log;
var _error = console.error;

var logger = Logger.setupDefaultLogger('YOUR API KEY', options);


var log = function() {
    logger.log([...arguments].join(' '));
    _log.apply(console, arguments);
};

var error = function() {
    logger.error([...arguments].join(' '));
    _error.apply(console, arguments);
};

/**
 * Pass the data to send as `event.data`, and the request options as
 * `event.options`. For more information see the HTTPS module documentation
 * at https://nodejs.org/api/https.html.
 *
 * Will succeed with the response body.
 */
exports.handler = (event, context, callback) => {
    console.log = log;
    console.error = error;

    // Your code here
    console.log('How bout normal log');
    console.error('Try an error');

    callback();
};

HTTP Exception Handling

If the logger does not receive a successful response from the server, it tries to send it again in the period set in options (options.retryTimeout) or the default BACKOFF_PERIOD. It makes three (or RETRY_TIMES) attempts to resend the logs. If none of the attempts was successful, the failed logs will be preserved and attempted to send with the next request. The size of the retry buffer that saves logs that failed to send and the retry timeout are configurable via:

var options = {
    failedBufRetentionLimit: 10000000 // bytes
    retryTimeout: 3000 // milliseconds
    retryTimes: 5
};

var logger = Logger.setupDefaultLogger(apikey, options);

Troubleshooting

This library takes advantage of util.debuglog() to output details about message handling such as:

  • When the logger receives a message (useful for indirect usages such as bunyan, winston, or custom wrappers)
  • An indication of when messages are actually sent to the API (they may be buffered for a time)
  • An indication of whether the API responds with a success or failure.

For cases where you do not see your log messages appear in LogDNA, these debug messages can make it easier to tell if the problem is on the sending or receiving end. They can also provide valuable information which can speed up diagnosis if you need to work with the LogDNA support staff.

You can enable debug messages with the NODE_DEBUG=logdna environment variable. See the util.debuglog() documentation for more information.

License

MIT ยฉ LogDNA

Happy Logging!

nodejs's People

Contributors

adamkingit avatar andkon avatar beefcheeks avatar choilmto avatar danawoodman avatar darinspivey avatar elsbree avatar fataltouch avatar ianwremmel avatar ibmjanneme avatar jbcpollak avatar jolg42 avatar logdnabot avatar martinross-ibm avatar mrjohnnychang avatar mvasigh avatar respectus avatar smusali avatar theoephraim avatar vilyapilya avatar weizou19 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nodejs's Issues

Client Side for IE11

Documentation says that I only need to run browserify main.js -o bundle.js to make it working in browser. And really when I did it and added my domain to white list (#52) it started working fine in Chrome.

But then I realized that it's not working in IE11 (arrow functions issue), I've spent much time to make logger work in IE11, that's why I decided to add this here.

  1. Run npm i babelify @babel/core @babel/cli @babel/preset-env in node_modules/logdna
  2. Add this to package.json
"browserify": {
    "transform": [
      [
        "babelify",
        {
          "presets": [
            [
              "@babel/preset-env",
              {
                "targets": {
                  "browsers": [
                    ">1%",
                    "last 4 versions",
                    "Firefox ESR",
                    "not ie < 11"
                  ]
                }
              }
            ]
          ]
        }
      ]
    ]
  }
  1. npm i -g browserify
  2. browserify index.js --standalone Logger -o bundle.js - after this lodna object will be available by window.Logger.

P. S. Sorry if I wrote it in wrong place

Can't use from browser-based applications

Now that LogDNA supports whitelisting of CORS domains, enabling ingesting logs directly from the browser, it would be great if this package also supported Browser-based applications via Webpack or Browserify.

I hacked something in to prove it could work but killed the server implementation in the process and wasn't sure the best way to support both between trying to use isomorphic-fetch or handling the two cases separately. Either way will require some refactoring but would like to get some advice from the maintainers if possible, particularly if there are any changes already planned for this lib.

Unable to resolve the 'utils' module with metro-bundle

Hello,

I'm currently trying to change my log system from logz.io to logDNA on my react-native application.

After creating a Logger just like in the README.md of the repo, I try to log a simple message with a valid JSON as metadata.
Screenshot from 2019-12-20 10-50-18

But when I launch my application with an emulator on android studio with metro-bundle, i'm getting an error saying that it can't find the 'utils' module used in lib/logger.js inside the node-modules

After searching a bit, I think that the missing 'utils' module is part of the basic node type library

Screenshot from 2019-12-20 10-41-05

Any idea of what may cause this ?

Truncating log messages

We have very long messages at times that get truncated in the log viewer:

image

Is there a way to turn that off?

Bump Axios to > `0.25.0`

Synkbot has recommended upgrading Axios due to some bug/security patches. We will do this manually in a new issue since the recommendation was blocked by #110

SIGINT and SIGTERM don't seem to be working, even after fix

Logdna keeps our server alive after we try to terminate with SIGINT. Here's Why we think it occurs (steps 1, 2, 3):

function onSignal(sigType) {
    var i = loggers.length;
    var finalize = process.listenerCount(sigType) > 1 ? function() {} : function() { process.exit(); };

    var expectedCallbacks = 0; // Step 1: expectedCallbacks set to zero
    function callback() {
        if (expectedCallbacks-- < 1) finalize(); // Step 3: expectedCallbacks is 1. Decrement is post fix, so comparison is if (1 < 1) which will always be false. finalize is not called
    };
    while (i--) {
        if (loggers[i][sigType]) {
            expectedCallbacks++; // Step 2: expectedCallbacks is set to 1
            loggers[i].logger._cleanUp(callback);
        }
    }
}

process.on('SIGTERM', onSignal.bind(null, 'SIGTERM'));
process.on('SIGINT', onSignal.bind(null, 'SIGINT'));

Is there something I'm missing? https://github.com/logdna/nodejs/blob/master/lib/logger.js#L244

Does console.log with messages!

The exclamation mark is because I ended up with over 1GB of log files on the server which left unchecked would have eventually used up all disk space had I not noticed. I think the console.log statements should be removed from the winston code.

TypeError: _winston2.default.transports.Logdna is not a constructor

If you follow the readme to setup with Winston it fails with:

TypeError: _winston2.default.transports.Logdna is not a constructor

Instead, one should import the constructor and use that:

import { WinstonTransport } from 'logdna'

//...

winston.add(WinstonTransport, { /* options */ })

The readme should probably be updated accordingly?

Repo naming is a bit confusing

Right now it says "Fork Node.js", "Fork Ruby", but IMHO it would be better to have LogDNA in the repo name. It might seem repetitive but would make it more clear and better SEO :)

Cheers!

screen shot 2018-02-23 at 3 43 28 pm

LogDNA Winston Transport in typescript

How can one use the LogDNA Winston Transport using Typescript? The line
winston.add(winston.transports.Logdna, options);
causes: Property 'Logdna' does not exist on type 'Transports'.

Any help is appreciated.

Add option to only print out logs in the console

Is there a way to NOT send out the logs to the LogDNA platform and just print them in the console? Basically I don't want to send out logs in test or local environment, but I still want to see them in the console.

No meta object without "index_meta: true" but parsing error with "index_meta: true" if meta object contains "data"-key

These are actually two issues:

First one - we cannot see a meta object in the logs if we don't set index_meta to true. This worked before with the same setup.

How to reproduce:

createLogger("123123123", {
    app: "test-service",
    hostname: "path.to.host.com",
    env: "localhost"
})
logger.log("Hello Log", { 
    meta: {
        foo: "bar"
    }
})

Second one - setting index_meta to true solves the behaviour described above. But it produces a parsing error if the meta object contains an object called data.

How to reproduce:

createLogger("123123123", {
    app: "test-service",
    hostname: "path.to.host.com",
    env: "localhost",
    index_meta: true
})
logger.log("Hello Log", { 
    meta: {
        data: {
            foo: "bar"
        }
    }
})

Unable to turn off `index_meta` on message level

The logic to check if the message meta should be index or not is causing all messages to be index, even if you specify index_meta: false at the message level.

This is because if the logger options is set to index_meta: true, the condition this._index_meta || opts.index_meta will always be true. It should be something like

if (opts.index_meta || (opts.index_meta === undefined && this._index_meta))

Steps to reproduce

const logdna = require('logdna');

var logger = logdna.createLogger(process.env.LOG_DNA_KEY, { index_meta: true });
logger.info('test', { index_meta: false, meta: { extra_info: 'aaaa' } });

Expected result

Message meta not index

Observed result

Message meta is indexed

Replace CirlcleCI with Jenkins

We need to keep this repository up-to-date enough with CI to ensure that we can apply patches. Synk has identified that Axios needs to be upgraded.

  • Change to Jenkins

Error: Tags is undefined or not passed as a String

When using the example from the README, I get this error Error: Tags is undefined or not passed as a String

// Add tags in array or comma-separated string format:
options.tags = ['logging', 'nodejs', 'logdna'];

It works fine with the alternative, as a string with commas.
Maybe you should remove the array method from the README or fix it?

Emit events at important points

Currently when an error occurs, such as on flush, and other points debug is used to output information - ie.
https://github.com/logdna/nodejs/blob/master/lib/logger.js#L254

However, as a user of the library I would like to take action if this occurs - such as emit a custom metric or trigger some operational response if it continues to occur.

A solution would be to emit events:
https://nodejs.org/docs/latest-v10.x/api/events.html

Some points I initially promose to emit events from would be:

Ambient meta

It would be really helpful to be able to add ambient meta properties to logs, a la Serilog. For example, when handling an incoming HTTP request, it would be great to give that request a correlation ID and have all further logging that occurs on that request include that correlation ID.

Using LogDNA in Electron

Hello,

I have an electron app that is bundle with React application. I am trying to use logDNA from inside React views on Electron.

It works fine during development as Electron serves the react application via a local dev server as long as I have http://localhost in the whitelisted domain in the settings on LogDNA.

However, electron app simply serves the React index.html via file:// in production build. These logs are not showing up in LogDNA. See the error trace from network tab:

Screenshot 2020-08-21 at 4 29 35 PM

I tried to add file:// as whitelisted domain from LogDNA but it won't let me.

Screenshot 2020-08-21 at 4 31 38 PM

Error (from network tab): Invalid value for domain: file://

Any pointers in this regard would be greatly appreciated.

Sync recent updates to npm

The README mentions createLogger, but the most recent version from npm doesn't work as described. The optional params (mac, IP, etc) would be helpful, as well.

Chrome & Safari: Refused to set unsafe header "user-agent"

Description

This library sets the user-agent header on each request. In the browser (Chrome and Safari specifically) this triggers an error logged from XHR's setRequestHeader() as Chrome and Safari treat user-agent as a forbidden header name:

Example (Chrome):
Screen Shot 2019-12-02 at 2 10 14 PM

user-agent is actually no longer a forbidden header name per spec and this works fine in Firefox, so Chrome and Safari are not spec-compliant in this regard. Also, the XHR still fires successfully, so this error doesn't break anything. However, it is quite annoying/disruptive to see the error messages pile up in the console.

Expected behavior

No errors are logged with outgoing XHR requests

Current behavior

Each outgoing XMLHttpRequest in the browser logs an error emitted from setRequestHeader when setting the user-agent header.

LogDNA keeps AWS lambda running until timeout

I am working on migrating an existing microservice cluster onto a serverless node stack based on AWS Lambda.

I was already using LogDNA before with no problems, but I ran into an issue when writing the lambdas. They all seemed to hang until the timeout, never completing successfully.

After some troubleshooting I figured out that if I set context.callbackWaitsForEmptyEventLoop to true the lambda finishes.

After some more digging I figured out that it was actually LogDNA keeping the lambda up and preventing it from completing.

Is this something that can be addressed? Or is it something in the core functionality of the library and I'll just have to figure out some way around it?

Sequelize raw object not logged and freezes the whole application

Node.js: 8.9.1
logdna: ^1.4.0
bunyan: ^1.8.12
logdna module part: BunyanStream
sequelize: ^4.8.4

How to reproduce:

  1. Run an application where you use Bunyan and LogDNA's BunyanStream sub-module to log, and Sequelize for DB connection.
  2. Try log a raw, unformatted Sequelize object

What happens:
The log is not executed (the information is not logged and does not reach LogDNA).
The server app freezes.

More info:
So, this is the unformatted Sequelize object that is trying to get logged:

[ registration {
    dataValues:
     { id: '1',
       customerId: '1',
       date: '2017-10-10',
       userId: '1',
       amount: 1800,
       unit: 'kg',
       currency: 'DKK',
       kgPerLiter: 15,
       cost: '5000',
       comment: 'Hello test',
       manual: true,
       scale: 'true',
       updatedAt: 2017-10-09T10:30:42.000Z,
       createdAt: 2017-10-09T10:30:42.000Z,
       deletedAt: null,
       areaId: '2',
       productId: '2',
       area_id: '2',
       product_id: '2' },
    _previousDataValues:
     { id: '1',
       customerId: '1',
       date: '2017-10-10',
       userId: '1',
       amount: 1800,
       unit: 'kg',
       currency: 'DKK',
       kgPerLiter: 15,
       cost: '5000',
       comment: 'Hello test',
       manual: true,
       scale: 'true',
       updatedAt: 2017-10-09T10:30:42.000Z,
       createdAt: 2017-10-09T10:30:42.000Z,
       deletedAt: null,
       areaId: '2',
       productId: '2',
       area_id: '2',
       product_id: '2' },
    _changed: {},
    _modelOptions:
     { timestamps: true,
       validate: {},
       freezeTableName: true,
       underscored: false,
       underscoredAll: false,
       paranoid: true,
       rejectOnEmpty: false,
       whereCollection: [Object],
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},
       scopes: [],
       hooks: {},
       indexes: [Object],
       name: [Object],
       omitNull: false,
       getterMethods: [Object],
       sequelize: [Object],
       uniqueKeys: {} },
    _options:
     { isNewRecord: false,
       _schema: null,
       _schemaDelimiter: '',
       raw: true,
       attributes: [Object] },
    __eagerlyLoadedAssociations: [],
    isNewRecord: false } ]

It does not get logged and the whole app freezes, becoming unresponsive to further requests.
Nevertheless, if I format the object into the actual thing that has to be logged:

[
    {
        "date": "2017-10-10",
        "createdAt": "2017-10-09 10:30:42",
        "updatedAt": "2017-10-09 10:30:42",
        "id": "1",
        "customerId": "1",
        "userId": "1",
        "amount": 1800,
        "unit": "kg",
        "currency": "DKK",
        "kgPerLiter": 15,
        "cost": "5000",
        "comment": "Hello test",
        "manual": true,
        "scale": "true",
        "deletedAt": null,
        "areaId": "2",
        "productId": "2",
        "area_id": "2",
        "product_id": "2"
    }
]

Then it works all fine.

Of course, I don't want to log the unformatted object, because it contains a lot of redundant data, and I am going to format my objects before logging them.
I just thought it'd be nice to let you know about this issue.

Listener Leak

Hi,

I'm getting a listener leak when I use the logger. I've attached a chrome performance monitor snapshot.

The "ingest" blocks stand for:

image

image

import {ConstructorOptions, createLogger, Logger} from "logdna";
import {hostname} from "os";
import {logDNAKey} from "../settings";
import {env} from "./env";

class LogDNALogger {
    private logger: Logger;
    private user: string;
    constructor() {

        const options: ConstructorOptions = {
            app: "live-data-entry-desktop",
            env: env(),
            hostname: hostname(),
        };

        // @ts-ignore
        options.index_meta = true;
        this.logger = createLogger(logDNAKey, options);
    }

    public log(message: string) {
      this.logger.log(message);
    }
}

export const logger = new LogDNALogger();

Bumped into 400 error without body when tried to use on Client side

Hi!

Documentation says that I can use lib in browser, right?

My code looks like:

import Logger from 'logdna';
...
const logger = Logger.createLogger(token, {
  hostname: 'ClientSideTest',
  app: 'test',
});
logger.log('Hello LogDNA Test ', { meta: { sequence: 1 } });

On network tab of Chrome dev tools I see OPTIONS request with status=200 and another request with status=400 and without response body, so I do not have idea what I did wrongly...
https://prnt.sc/nstdxd

I would like to notify that these code is used in react app and it's built with webpack.

Can you help me, please?

latest 1.4.1 does not work with Node < 6+

the latest update 1.4.1 does not work in versions of Node below 6x. We are currently using Node 5.12 and logdna fails due to calls to process.emitWarning (this does not exist in Node 5)

Log metadata from different lines being merged

Since we installed the most recent version of this library, we've been seeing metadata from log lines getting merged (see issue on logdna-winston). I believe this is due to this change from #66.

The line that was added is:

opts.meta = Object.assign(message.meta, opts.meta);

The problem with this is that message.meta is a reference to this._meta (assigned here), which is the default metadata object for all log lines. So the line above actually merges opts.meta into the default metadata object every time the log function is called, causing the default metadata object to grow in size and contain all keys from all previous log lines.

I'll submit a PR for this- I think the easy solution is to change the above line to

opts.meta = Object.assign({}, message.meta, opts.meta);

Singleton example not working

My apologies if this is user error...

This doesn't work:

var options = {
    hostname: 'localhost',
    app: 'app-name'
};
var logger = Logger. setupDefaultLogger('KEY', options);  //singleton
logger.log('test');  //never arrives on logdna

This does:

var options = {
    hostname: 'localhost',
    app: 'app-name'
};
var logger = Logger.createLogger('KEY', options);
logger.log('test');

Winston dependency

It would be better to have the winston transport be a separate module, so that non-winston-users don't have add it as an indirect dependency.

Please?

Typescript support

Hi,

I'm using this module with typescript but since there is no typescript definition file I had to create my own:

declare module "logdna" {
  interface Options {
    app?: string,
    hostname?: string,
    env?: string,
    index_meta?: boolean,
    ip?: string,
    level?: 'Debug' | 'Trace' | 'Info' | 'Warn' | 'Error' | 'Fatal',
    mac?: string,
    max_length?: boolean,
    timeout?: number,
    with_credentials?: boolean
  }
  interface LogOptions extends Options {
    meta?: Object
  }
  export interface LogDna {
    log: (line: string, options?: LogOptions) => void;
  }

  export function createLogger(key: string, options?: Options): LogDna;
  export function flushAll(): void;
  export function cleanUpAll(): void;
}

Is this something you want to add in to this project?

This can easily be done by creating a new file in this project types.d.ts and then add types: "types.d.ts" in package.json.

I can create a PR if you want.

Not all logs being delivered on graceful shutdown.

Hey,

I'm using Logdna w/ bunyan. On SIGTERM my logs are being logged to console but don't make it to logdna. I see you have some sort of message buffer. Is there a way to flush it manually or another way to persist the logs to your app?

tags array type throw an error

in readme:

// Add tags in array or comma-separated string format:
options.tags = ['logging', 'nodejs', 'logdna'];
// or:
options.tags = 'logging,nodejs,logdna';

in code all options are checked by the function checkParam which throw an error if typeof param !== 'string'

This option should not be checked by checkParam just like other options type (cf index_meta for example).

Not handling exceptions

winston 2.2.0, logdna 1.1.7:

    winston.add(winston.transports.Logdna, {
      key: process.env.LOGDNA_APIKEY
      hostname: "api.mwater.co"
      app: "mwater-prod"
      max_length: false
      handleExceptions: true
    })

Doesn't emit errors to the log, it seems. Am I doing something wrong?

this.log is not a function

Logdna v2.0.2
I get this error when running on node:alpine docker container (node 9.x)

at Logger.(anonymous function) (/node_modules/logdna/lib/logger.js:230:14)
UnhandledPromiseRejectionWarning: TypeError: this.log is not a function

Any idea why this could be happening?

SIGINT handler causes process to hang when interrupted

Flushing logs on SIGINT and SIGTERM is a nice idea, but since you don't then call process.exit() the node process hangs after the logs have been flushed:

https://github.com/logdna/nodejs/blob/master/lib/logger.js#L232

Of course, calling process.exit() will also be a problem, because if an app registers its own handler, that probably won't get called since logdna is exiting before the app's handler gets to run.

You could be clever, and see if there are any handlers that are supposed to run after yours, or just make it another configuration option. Either way, you probably shouldn't register the handler if no loggers are configured to flush anyway.

Doesn't work on Zeit's NOW

I used LogDNA on a Now lambda and after the functions are executed, logs don't show because the function executed completely and the logs aren't pushed. I had to add a delay of 5s for this to work.

Initial Code

const Logger = require("logdna");

const options = {
  hostname: "app",
  ip: "10.1.1.1",
  app: "pp"
};

const log = Logger.setupDefaultLogger(
  "KEY",
  options
);

module.exports = async (req, res) => {
  log.info(`${req.method} request`);
  res.end("OK");
};

Fix

const Logger = require("logdna");

const options = {
  hostname: "app",
  ip: "10.1.1.1",
  app: "pp"
};

const log = Logger.setupDefaultLogger(
  "KEY",
  options
);

module.exports = async (req, res) => {
  log.info(`${req.method} request`);
  await delay();
  res.end("OK");
};

const delay = async () => {
  await sleep(5000);
};

also would like to know if the log functions could return a Promise.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.