---
title: Node.js Log Collection
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Log Management > Log Collection and Integrations > Node.js Log
  Collection
---

> For the complete documentation index, see [llms.txt](https://docs.datadoghq.com/llms.txt).

# Node.js Log Collection

## Configure your logger{% #configure-your-logger %}

To send your logs to Datadog, log to a file and [tail](https://docs.datadoghq.com/glossary.md#tail) that file with your Datadog Agent. Use a logging library, such as [Winston](https://github.com/winstonjs/winston), [Bunyan](https://github.com/trentm/node-bunyan), or [Pino](https://getpino.io/), to log from your Node.js application. The examples on this page use Winston.

Winston is available through [NPM](https://www.npmjs.com). To get started, add the dependency to your code:

```text
npm install --save winston
```

`package.json` is updated with the corresponding dependencies:

```js
{
  "name": "...",

  //...
  "dependencies": {
    //...
    "winston": "x.y.z",
    //...
  }
}
```

### Log to a file{% #log-to-a-file %}

In your bootstrap file or in your code, declare the logger in the following way:

{% tab title="Winston 3.0" %}

```js

const { createLogger, format, transports } = require('winston');

const logger = createLogger({
  level: 'info',
  exitOnError: false,
  format: format.combine(format.timestamp(), format.json()),
  transports: [
    new transports.File({ filename: `${appRoot}/logs/<FILE_NAME>.log` }),
  ],
});

module.exports = logger;

// Example logs
logger.log('info', 'Hello simple log!');
logger.info('Hello log with metas',{color: 'blue' });
```

{% /tab %}

{% tab title="Winston 2.0" %}

```js
var winston = require('winston');

var logger = new (winston.Logger)({
    transports: [
        new (winston.transports.File)({
            name: '<LOGGER_NAME>',
            filename: '<FILE_NAME>.log',
            json: true,
            level: 'info'
        })
    ]
});

// Example logs
logger.log('info', 'Hello simple log!');
logger.info('Hello log with metas',{color: 'blue' });
```

{% /tab %}

Check the content of the `<FILE_NAME>.log` file to confirm that Winston is logging in JSON:

```json
{"level":"info","message":"Hello simple log!","timestamp":"2015-04-23T16:52:05.337Z"}
{"color":"blue","level":"info","message":"Hello log with metas","timestamp":"2015-04-23T16:52:05.339Z"}
```

## Configure your Datadog Agent{% #configure-your-datadog-agent %}

After [log collection is enabled](https://docs.datadoghq.com/agent/logs.md?tab=tailfiles#activate-log-collection), set up [custom log collection](https://docs.datadoghq.com/agent/logs.md?tab=tailfiles#custom-log-collection) to tail your log files and send new logs to Datadog.

1. Create a `nodejs.d/` folder in the `conf.d/` [Agent configuration directory](https://docs.datadoghq.com/agent/configuration/agent-configuration-files.md?tab=agentv6v7#agent-configuration-directory).
1. Create a `conf.yaml` file in `nodejs.d/` with the following content:

```yaml
init_config:

instances:

##Log section
logs:

  - type: file
    path: "<FILE_NAME_PATH>.log"
    service: <SERVICE_NAME>
    source: nodejs
    sourcecategory: sourcecode
```
[Restart the Agent](https://docs.datadoghq.com/agent/configuration/agent-commands.md?tab=agentv6v7#restart-the-agent).Run the [Agent's status subcommand](https://docs.datadoghq.com/agent/configuration/agent-commands.md?tab=agentv6v7#agent-status-and-information) and look for `nodejs` under the Checks section to confirm logs are successfully submitted to Datadog.
If logs are in JSON format, Datadog automatically [parses the log messages](https://docs.datadoghq.com/logs/log_configuration/parsing.md?tab=matchers) to extract log attributes. Use the [Log Explorer](https://docs.datadoghq.com/logs/explorer.md#overview) to view and troubleshoot your logs.

## Connect your service across logs and traces{% #connect-your-service-across-logs-and-traces %}

If APM is enabled for this application, connect your logs and traces by [following the APM Node.js instructions](https://docs.datadoghq.com/tracing/other_telemetry/connect_logs_and_traces/nodejs.md). This automatically adds trace IDs, span IDs, `env`, `service`, and `version` to your logs.

**Note**: If the Datadog SDK injects `service` into your logs, it overrides the value set in the Agent configuration.

## Agentless logging{% #agentless-logging %}

You can stream your logs from your application to Datadog without installing an Agent on your host. However, Datadog recommends you use an Agent to forward your logs as it provides a native connection management.

Use the [Winston HTTP transport](https://github.com/winstonjs/winston/blob/master/docs/transports.md#http-transport) to send your logs directly through the [Datadog Log API](https://docs.datadoghq.com/api/v1/logs.md#send-logs). In your bootstrap file or in your code, declare the logger in the following way:

```javascript
const { createLogger, format, transports } = require('winston');

const httpTransportOptions = {
  host: 'http-intake.logs.<YOUR_DATADOG_SITE>',
  path: '/api/v2/logs?dd-api-key=<DATADOG_API_KEY>&ddsource=nodejs&service=<APPLICATION_NAME>',
  ssl: true
};

const logger = createLogger({
  level: 'info',
  exitOnError: false,
  format: format.json(),
  transports: [
    new transports.Http(httpTransportOptions),
  ],
});

module.exports = logger;

// Example logs
logger.log('info', 'Hello simple log!');
logger.info('Hello log with metas',{color: 'blue' });
```

**Note:** You can also use the community-supported [Datadog Transport](https://github.com/winstonjs/winston/blob/master/docs/transports.md#datadog-transport).

## Troubleshooting{% #troubleshooting %}

If you have DNS lookup errors in your application this could be due to logstash exceptions not being caught. A handler should be added as follows:

```js
var logstash = new winston.transports.Logstash({ ... });
logstash.on('error', function(err) {
    console.error(err); // replace with your own functionality here
});
```

Make sure that the parameter `max_connect_retries` is not set to `1` (the default is `4`).

## Further Reading{% #further-reading %}

Additional helpful documentation, links, and articles:

- [Learn how to process your logs](https://docs.datadoghq.com/logs/log_configuration/processors.md)
- [Learn more about parsing](https://docs.datadoghq.com/logs/log_configuration/parsing.md)
- [Learn how to explore your logs](https://docs.datadoghq.com/logs/explorer.md)
- [Perform Log Analytics](https://docs.datadoghq.com/logs/explorer.md#visualize)
- [Log Collection Troubleshooting Guide](https://docs.datadoghq.com/logs/faq/log-collection-troubleshooting-guide.md)
- [Glossary entry for "tail"](https://docs.datadoghq.com/glossary.md#tail)
