To send your logs to Datadog, log to a file and tail that file with your Datadog Agent. Use the Winston logging library to log from your Node.js application.
Winston is available through NPM, to get started, you want to add the dependency to your code:
npm install --save winston
package.json is updated with the corresponding dependencies:
const{createLogger,format,transports}=require('winston');constlogger=createLogger({level:'info',exitOnError:false,format:format.json(),transports:[newtransports.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'});
varwinston=require('winston');varlogger=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'});
Check the content of the <FILE_NAME>.log file to confirm that Winston is logging in 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"}
Run the Agent’s status subcommand 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 to extract log attributes. Use the Log Explorer to view and troubleshoot your logs.
If APM is enabled for this application, connect your logs and traces by automatically adding trace IDs, span IDs,
env, service, and version to your logs by following the APM Node.js instructions.
Note: If the APM tracer injects service into your logs, it overrides the value set in the Agent configuration.
You can stream your logs from your application to Datadog without installing an Agent on your host. However, it is recommended that you use an Agent to forward your logs as it provides a native connection management.
Use the Winston HTTP transport to send your logs directly through the Datadog Log API.
In your bootstrap file or in your code, declare the logger in the following way:
const{createLogger,format,transports}=require('winston');consthttpTransportOptions={host:'http-intake.logs.datadoghq.com',path:'/api/v2/logs?dd-api-key=<DATADOG_API_KEY>&ddsource=nodejs&service=<APPLICATION_NAME>',ssl:true};constlogger=createLogger({level:'info',exitOnError:false,format:format.json(),transports:[newtransports.Http(httpTransportOptions),],});module.exports=logger;// Example logs
logger.log('info','Hello simple log!');logger.info('Hello log with metas',{color:'blue'});