| copyright |
|
||
|---|---|---|---|
| lastupdated | 2018-08-15 |
{:new_window: target="_blank"} {:shortdesc: .shortdesc} {:screen: .screen} {:codeblock: .codeblock} {:pre: .pre} {:tip: .tip}
{: #logging_nodejs}
Logs are required to diagnose how and why services either failed or are behaving erroneously. Given the transient nature of processes in Cloud environments, logs must be collected and sent elsewhere, usually to a centralized location for analysis. Unlike appmetrics, logs are not meant to be used for measuring application performance. Ideally, applications emit logs as event streams, rely on the environment to collect them, and send them to the right places.
Apps can be designed to emit logs in JSON format natively so that the logs can be parsed independently of the log aggregation technology (or dashboards) that are used. Or, you might want to use a custom parser with custom dashboards for enhanced monitoring.
{: #add_log4j}
Log4js is a popular logging framework for Node.js, and provides many native benefits, which include:
- Logging to
stdoutorstderr - Various appending options
- Configurable log message layout and patterns
- Using Log Levels for different log categories
- To use Log4js, run the following command in the root directory of your application, which installs the package and adds it to your
package.jsonfile.
npm install --save log4js{: codeblock}
- To use it in your application, add the following lines of code:
var log4js = require('log4js');
var log = log4js.getLogger();
log.level = 'debug';
log.debug("My Debug message");{: codeblock}
stdout Output:
[2018-07-21 10:23:57.881] [DEBUG] [default] - My Debug message
{: screen}
For more information about customizing the log messages with appenders, Log Levels, and configuration details, see the official log4js-node documentation.
{: #monitoring}
Node.js apps that are created by using the {{site.data.keyword.cloud_notm}} AppService come with Log4js by default. Running the app natively or in a Cloud environment produces output like: 2018-07-26 12:40:15.121] [INFO] MyAppName - MyAppName listening on http://localhost:3000. You can view the output as follows:
- Use
stdoutwhen you run locally. - In the logs for CloudFoundry and Kubernetes deployments, which are accessed by
ibmcloud app logs --recent <APP_NAME>andkubectl logs <deployment name>.
In the server/server.js file, you can see the following code:
const logger = log4js.getLogger(appName);
const app = express();
app.use(log4js.connectLogger(logger, { level: process.env.LOG_LEVEL || 'info' }));{: codeblock}
By default, the Log Level is set to INFO, and can be overridden by the application's LOG_LEVEL environment variable.
{: tip}
{: #next_steps notoc}
Learn more about viewing the logs in each of our deployment environments:
Using a Log aggregator: