Package detail

@google-cloud/logging-bunyan

googleapis280.7kApache-2.05.1.0

Cloud Logging stream for Bunyan

google apis client, google api client, google apis, google api

readme

Google Cloud Platform logo

Cloud Logging for Bunyan: Node.js Client

release level npm version

This module provides an easy to use, higher-level layer for working with Cloud Logging, compatible with Bunyan. Simply attach this as a transport to your existing Bunyan loggers.

A comprehensive list of changes in each version may be found in the CHANGELOG.

Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

Table of contents:

Quickstart

Before you begin

  1. Select or create a Cloud Platform project.
  2. Enable the Cloud Logging for Bunyan API.
  3. Set up authentication with a service account so you can access the API from your local workstation.

Installing the client library

npm install @google-cloud/logging-bunyan

Using the client library

const bunyan = require('bunyan');

// Imports the Google Cloud client library for Bunyan
const {LoggingBunyan} = require('@google-cloud/logging-bunyan');

// Creates a Bunyan Cloud Logging client
const loggingBunyan = new LoggingBunyan();

// Create a Bunyan logger that streams to Cloud Logging
// Logs will be written to: "projects/YOUR_PROJECT_ID/logs/bunyan_log"
const logger = bunyan.createLogger({
  // The JSON payload of the log as it appears in Cloud Logging
  // will contain "name": "my-service"
  name: 'my-service',
  streams: [
    // Log to the console at 'info' and above
    {stream: process.stdout, level: 'info'},
    // And log to Cloud Logging, logging at 'info' and above
    loggingBunyan.stream('info'),
  ],
});

// Writes some log entries
logger.error('warp nacelles offline');
logger.info('shields at 99%');

Using as an express middleware

NOTE: this feature is experimental. The API may change in a backwards incompatible way until this is deemed stable. Please provide us feedback so that we can better refine this express integration.

We provide a middleware that can be used in an express application. Apart from being easy to use, this enables some more powerful features of Cloud Logging: request bundling. Any application logs emitted on behalf of a specific request will be shown nested inside the request log as you see in this screenshot:

Request Bundling Example

The middleware adds a bunyan-style log function to the request object. You can use this wherever you have access to the request object (req in the sample below). All log entries that are made on behalf of a specific request are shown bundled together in the Cloud Logging UI.

const lb = require('@google-cloud/logging-bunyan');

// Import express module and create an http server.
const express = require('express');

async function startServer() {
  const {logger, mw} = await lb.express.middleware();
  const app = express();

  // Install the logging middleware. This ensures that a Bunyan-style `log`
  // function is available on the `request` object. Attach this as one of the
  // earliest middleware to make sure that log function is available in all the
  // subsequent middleware and routes.
  app.use(mw);

  // Setup an http route and a route handler.
  app.get('/', (req, res) => {
    // `req.log` can be used as a bunyan style log method. All logs generated
    // using `req.log` use the current request context. That is, all logs
    // corresponding to a specific request will be bundled in the Cloud UI.
    req.log.info('this is an info log message');
    res.send('hello world');
  });

  // `logger` can be used as a global logger, one not correlated to any specific
  // request.
  logger.info({port: 8080}, 'bonjour');

  // Start listening on the http server.
  app.listen(8080, () => {
    console.log('http server listening on port 8080');
  });
}

startServer();

Error Reporting

Any Error objects you log at severity error or higher can automatically be picked up by Cloud Error Reporting if you have specified a serviceContext.service when instantiating a LoggingBunyan instance:

const loggingBunyan = new LoggingBunyan({
  serviceContext: {
    service: 'my-service', // required to report logged errors
                           // to the Google Cloud Error Reporting
                           // console
    version: 'my-version'
  }
});

It is an error to specify a serviceContext but not specify serviceContext.service.

Make sure to add logs to your uncaught exception and unhandled rejection handlers if you want to see those errors too.

You may also want to see the [@google-cloud/error-reporting][@google-cloud/error-reporting] module which provides direct access to the Error Reporting API.

Special Payload Fields in LogEntry

There are some fields that are considered special by Google cloud logging and will be extracted into the LogEntry structure. For example, severity, message and labels can be extracted to LogEntry if included in the bunyan log payload. These special JSON fields will be used to set the corresponding fields in the LogEntry. Please be aware of these special fields to avoid unexpected logging behavior.

LogEntry Labels

If the bunyan log record contains a label property where all the values are strings, we automatically promote that property to be the LogEntry.labels value rather than being one of the properties in the payload fields. This makes it easier to filter the logs in the UI using the labels.

logger.info({labels: {someKey: 'some value'}}, 'test log message');

All the label values must be strings for this automatic promotion to work. Otherwise the labels are left in the payload.

Formatting Request Logs

To format your request logs you can provide a httpRequest property on the bunyan metadata you provide along with the log message. We will treat this as the HttpRequest message and Cloud logging will show this as a request log. Example:

Request Log Example

logger.info({
  httpRequest: {
    status: res.statusCode,
    requestUrl: req.url,
    requestMethod: req.method,
    remoteIp: req.connection.remoteAddress,
    // etc.
  }
}, req.path);

The httpRequest property must be a properly formatted HttpRequest message. (Note: the linked protobuf documentation shows snake_case property names, but in JavaScript one needs to provide property names in camelCase.)

Correlating Logs with Traces

If you use [@google-cloud/trace-agent][trace-agent] module, then this module will set the Cloud Logging [LogEntry][LogEntry] trace property based on the current trace context when available. That correlation allows you to [view log entries][trace-viewing-log-entries] inline with trace spans in the Cloud Trace Viewer. Example:

Logs in Trace Example

If you wish to set the Cloud LogEntry trace property with a custom value, then write a Bunyan log entry property for 'logging.googleapis.com/trace', which is exported by this module as LOGGING_TRACE_KEY. For example:

const bunyan = require('bunyan');
// Node 6+
const {LoggingBunyan, LOGGING_TRACE_KEY} = require('@google-cloud/logging-bunyan');
const loggingBunyan = LoggingBunyan();

...

logger.info({
  [LOGGING_TRACE_KEY]: 'custom-trace-value'
}, 'Bunyan log entry with custom trace field');

Error handling with a default callback

The LoggingBunyan class creates an instance of Logging which creates the Log class from @google-cloud/logging package to write log entries. The Log class writes logs asynchronously and there are cases when log entries cannot be written when it fails or an error is returned from Logging backend. If the error is not handled, it could crash the application. One possible way to handle the error is to provide a default callback to the LoggingBunyan constructor which will be used to initialize the Log object with that callback like in the example below:

// Imports the Google Cloud client library for Bunyan
const {LoggingBunyan} = require('@google-cloud/logging-bunyan');
// Creates a client
const loggingBunyan = new LoggingBunyan({
  projectId: 'your-project-id',
  keyFilename: '/path/to/key.json',
  defaultCallback: err => {
      if (err) {
      console.log('Error occured: ' + err);
      }
  },
});

Alternative way to ingest logs in Google Cloud managed environments

If you use this library with the Cloud Logging Agent, you can configure the handler to output logs to process.stdout using the structured logging Json format. To do this, add redirectToStdout: true parameter to the LoggingBunyan constructor as in sample below. You can use this parameter when running applications in Google Cloud managed environments such as AppEngine, Cloud Run, Cloud Function or GKE. The logger agent installed on these environments can capture process.stdout and ingest it into Cloud Logging. The agent can parse structured logs printed to process.stdout and capture additional log metadata beside the log payload. It is recommended to set redirectToStdout: true in serverless environments like Cloud Functions since it could decrease logging record loss upon execution termination - since all logs are written to process.stdout those would be picked up by the Cloud Logging Agent running in Google Cloud managed environment. Note that there is also a useMessageField option which controls if "message" field is used to store structured, non-text data inside jsonPayload field when redirectToStdout is set. By default useMessageField is always true. Set the skipParentEntryForCloudRun option to skip creating an entry for the request itself as Cloud Run already automatically creates such log entries. This might become the default behaviour in a next major version.

// Imports the Google Cloud client library for Bunyan
const {LoggingBunyan} = require('@google-cloud/logging-bunyan');

// Creates a client
const loggingBunyan = new LoggingBunyan({
  projectId: 'your-project-id',
  keyFilename: '/path/to/key.json',
  redirectToStdout: true,
});

Samples

Samples are in the samples/ directory. Each sample's README.md has instructions for running its sample.

Sample Source Code Try it
Express source code Open in Cloud Shell
Quickstart source code Open in Cloud Shell
Explict Auth Setup source code Open in Cloud Shell

The Cloud Logging for Bunyan Node.js Client API Reference documentation also contains samples.

Supported Node.js Versions

Our client libraries follow the Node.js release schedule. Libraries are compatible with all current active and maintenance versions of Node.js. If you are using an end-of-life version of Node.js, we recommend that you update as soon as possible to an actively supported LTS version.

Google's client libraries support legacy versions of Node.js runtimes on a best-efforts basis with the following warnings:

  • Legacy versions are not tested in continuous integration.
  • Some security patches and features cannot be backported.
  • Dependencies cannot be kept up-to-date.

Client libraries targeting some end-of-life versions of Node.js are available, and can be installed through npm dist-tags. The dist-tags follow the naming convention legacy-(version). For example, npm install @google-cloud/logging-bunyan@legacy-8 installs client libraries for versions compatible with Node.js 8.

Versioning

This library follows Semantic Versioning.

This library is considered to be stable. The code surface will not change in backwards-incompatible ways unless absolutely necessary (e.g. because of critical security issues) or with an extensive deprecation period. Issues and requests against stable libraries are addressed with the highest priority.

More Information: Google Cloud Platform Launch Stages

Contributing

Contributions welcome! See the Contributing Guide.

Please note that this README.md, the samples/README.md, and a variety of configuration files in this repository (including .nycrc and tsconfig.json) are generated from a central template. To edit one of these files, make an edit to its templates in directory.

License

Apache Version 2.0

See LICENSE

changelog

Changelog

npm history

5.1.0 (2024-01-31)

Features

  • Enable custom json fields truncation for bunyan (#732) (eb6fa66)

Bug Fixes

  • Add speciel logging fields section in the doc (#728) (0b9ad2b)
  • Fix rest links with the correct gRPC links used by library. (#724) (555c33e)

5.0.1 (2023-10-30)

Bug Fixes

  • deps: Update dependency @google-cloud/logging to v11 (d740098)

5.0.0 (2023-08-10)

⚠ BREAKING CHANGES

  • upgrade to Node 14 (#705)

Miscellaneous Chores

4.2.2 (2022-12-02)

Bug Fixes

  • Add a partner team as approvers for PRs (#677) (7b88e97)

4.2.1 (2022-11-07)

Bug Fixes

  • Switch instrumentation code to return version stored in NODEJS_BUNYAN_DEFAULT_LIBRARY_VERSION (#672) (2eb88d8)

4.2.0 (2022-11-04)

Features

  • Add support for instrumentation version annotations (#670) (e332a76)

4.1.5 (2022-11-01)

Bug Fixes

  • Prevent instrumentation crash and fix the system test (#666) (4e12496)

4.1.4 (2022-10-12)

Bug Fixes

4.1.3 (2022-10-10)

Bug Fixes

  • Skip parent request entry on cloud run (#658) (226972e)

4.1.2 (2022-08-25)

Bug Fixes

  • remove pip install statements (#1546) (#649) (0fdd9ec)
  • Update latest logging-nodejs to repaire google-gax vulnerability (#651) (857de69)

4.1.1 (2022-07-18)

Bug Fixes

  • Logging to stdout in Cloud Run creates a JSON object as "message" (#644) (41eaaa8)

4.1.0 (2022-06-02)

Features

  • Add support for library instrumentation (#631) (39e0193)

4.0.0 (2022-05-20)

⚠ BREAKING CHANGES

  • update library to use Node 12 (#627)

Build System

3.3.1 (2022-04-15)

Bug Fixes

3.3.0 (2022-03-21)

Features

  • Logging provider for Cloud Functions that outputs structured logs to process.stdout (#605) (f3ed3aa)

3.2.2 (2022-03-09)

Bug Fixes

  • Use defaultCallback in LoggingBunyan class (#601) (f4c01ab)

3.2.1 (2022-03-02)

Bug Fixes

  • Update dependency @google-cloud/logging from 9.0.0 to 9.8.0 (#597) (a350362)

3.2.0 (2021-12-09)

Features

3.1.1 (2021-09-08)

Bug Fixes

3.1.0 (2021-06-15)

Features

3.0.2 (2021-02-09)

Bug Fixes

  • deps: update dependency google-auth-library to v7 (#513) (07e5830)

3.0.1 (2020-09-12)

Bug Fixes

  • deps: update dependency yargs to v16 (#484) (a307179)

3.0.0 (2020-05-20)

⚠ BREAKING CHANGES

  • drop support for node.js 8.x (#440)

Bug Fixes

Build System

2.0.3 (2020-01-24)

Bug Fixes

2.0.2 (2019-12-05)

Bug Fixes

  • deps: TypeScript 3.7.0 causes breaking change in typings (#384) (b7c509c)

2.0.1 (2019-12-02)

Bug Fixes

  • deps: update dependency yargs to v15 (#377) (730bac9)
  • docs: snippets are now replaced in jsdoc comments (#371) (1cfbf8d)

2.0.0 (2019-10-18)

⚠ BREAKING CHANGES

  • truncate log messages > 250,000 bytes (#365)

Features

  • truncate log messages > 250,000 bytes (#365) (b712f12)

1.2.3 (2019-09-03)

Bug Fixes

  • deps: update dependency yargs to v14 (#346) (93f7deb)
  • docs: remove anchor from reference doc link (#348) (6937d45)

1.2.2 (2019-08-13)

Bug Fixes

  • deps: update dependency google-auth-library to v5 (#342) (f560753)

1.2.1 (2019-06-26)

Bug Fixes

  • docs: link to reference docs section on googleapis.dev (#338) (c576ae4)

1.2.0 (2019-06-24)

Features

  • add support for apiEndpoint override (#336) (5feb3c9)

1.1.1 (2019-06-14)

Bug Fixes

1.1.0 (2019-06-05)

Features

  • add .repo-metadata.json, generate docs (#328) (342a41e)

1.0.0 (2019-05-29)

⚠ BREAKING CHANGES

  • upgrade engines field to >=8.10.0 (#298)

Bug Fixes

  • proper signature for _write[v] (#287) (8bb305a)
  • deps: update dependency google-auth-library to v4 (#308) (e309b7c)

Build System

Features

v0.10.1

03-14-2019 14:58 PDT

Bug Fixes

  • fix: add missing dep on google-auth-library (#278)

v0.10.0

03-12-2019 16:24 PDT

New Features

  • feat(middleware): generate parent request logs (#235)

Bug Fixes

  • fix: do not promote record.labels if improper (#266)
  • fix: remove deep dependency into auth-library (#251)

Documentation

  • docs: update links in contrib guide (#263)
  • docs: update contributing path in README (#256)
  • docs: move CONTRIBUTING.md to root (#255)
  • docs: add lint/fix example to contributing guide (#252)
  • docs: use https for links (#246)

Internal / Testing Changes

  • chore: allow custom port in samples tests (#272)
  • build: Add docuploader credentials to node publish jobs (#270)
  • build: update release config (#268)
  • build: use node10 to run samples-test, system-test etc (#269)
  • chore(deps): update dependency mocha to v6 (#264)
  • build: use linkinator for docs test (#262)
  • fix: de-flake system tests (#261)
  • chore: resolve TODO in test (#259)
  • build: create docs test npm scripts (#258)
  • build: test using @grpc/grpc-js in CI (#257)
  • chore(deps): update dependency @google-cloud/common to ^0.31.0 (#253)
  • fix(deps): update dependency yargs to v13 (#260)
  • fix: directly depend on @g-c/common (#250)
  • chore(deps): update dependency eslint-config-prettier to v4 (#245)
  • build: ignore googleapis.com in doc link check (#242)
  • build: check broken links in generated docs (#239)
  • refactor: modernize the sample tests (#237)

v0.9.5

12-12-2018 19:50 PST

Bug Fixes

  • fix(middleware): use bunyan log.child (#163)
  • fix: Don't publish sourcemaps (#166)

Dependencies

  • fix(deps): update dependency @opencensus/propagation-stackdriver to ^0.0.6 (#192)
  • fix(deps): update dependency @opencensus/propagation-stackdriver to ^0.0.5 (#177)

Docs & Samples

  • docs: update readme badges (#213)
  • refactor: convert samples test from ava to mocha (#190)

Internal / Testing Changes

  • chore: the sample tests complete correctly (#232)
  • chore(build): inject yoshi automation key (#231)
  • chore: update nyc and eslint configs (#230)
  • chore: fix publish.sh permission +x (#228)
  • fix(build): fix Kokoro release script (#227)
  • build: add Kokoro configs for autorelease (#226)
  • chore: always nyc report before calling codecov (#222)
  • chore: nyc ignore build/test by default (#220)
  • refactor: reduce the number of dependencies (#206)
  • chore: clean up usage of prettier and eslint (#219)
  • chore: update system tests key (#216)
  • chore: add polling to system tests (#217)
  • chore: update license file (#215)
  • fix(build): fix system key decryption (#211)
  • chore(deps): update dependency typescript to ~3.2.0 (#209)
  • chore: update system tests key (#210)
  • chore: add synth.metadata
  • chore(deps): update dependency gts to ^0.9.0 (#202)
  • chore: update eslintignore config (#201)
  • chore(deps): update dependency @google-cloud/nodejs-repo-tools to v3 (#200)
  • chore: drop contributors from multiple places (#199)
  • refactor(middleware): use common code from logging (#197)
  • cleanup: remove unnecessary deps and files (#198)
  • chore: use latest npm on Windows (#196)
  • chore: update CircleCI config (#195)
  • chore: include build in eslintignore (#191)
  • chore(deps): update dependency eslint-plugin-node to v8 (#186)
  • fix(deps): update dependency @google-cloud/common to ^0.26.0 (#181)
  • chore: update issue templates (#185)
  • chore: remove old issue template (#183)
  • build: run tests on node11 (#182)
  • chores(build): do not collect sponge.xml from windows builds (#180)
  • chores(build): run codecov on continuous builds (#179)
  • chore: update new issue template (#178)
  • build: fix codecov uploading on Kokoro (#174)
  • Update kokoro config (#171)
  • chore(deps): update dependency eslint-plugin-prettier to v3 (#170)
  • chore(deps): update dependency typescript to ~3.1.0 (#169)

v0.9.4

Documentation

  • fix: doc string is malformed for jsdoc (#164)

v0.9.2

Bug Fixes

  • fix: logged errors are reported to error reporting (#122)
  • chore: fix stream example in README (#134)
  • fix(deps): update @google-cloud/logging to 4.x (#152)

Dependencies

  • fix(deps): update dependency @google-cloud/common to ^0.25.0 (#150)
  • chore(deps): update dependency delay to v4 (#142)
  • fix(deps): update dependency @google-cloud/common to ^0.24.0 (#146)
  • fix(deps): update dependency @opencensus/propagation-stackdriver to ^0.0.4 (#141)
  • fix(deps): update dependency @google-cloud/common to ^0.23.0 (#139)
  • fix(deps): update samples dependency @google-cloud/logging-bunyan to ^0.9.0 (#137)
  • chore(deps): update dependency execa to v1 (#138)

Internal / Testing Changes

  • Enable prefer-const in the eslint config (#151)
  • Enable no-var in eslint (#149)
  • Update CI config (#147)
  • Add synth script and update CI (#144)
  • Retry npm install in CI (#143)
  • chore(deps): update dependency nyc to v13 (#140)

v0.9.1

Fixes

  • chore: fix install tests (#133)

v0.9.0

Breaking changes

  • fix: drop support for node.js 4.x and 9.x (#87)
  • fix: drop support for node 4.x and 9.x (#69)

Features

  • feat: request-correlating middleware (#63)

Docs & Samples

  • chore: require node 8 for samples (#107)
  • doc: add express middleware to README (#97)
  • doc: fix typo in samples/README (#99)
  • fix: fix linting errors in the samples (#100)
  • feat(samples): add express middleware sample (#95)
  • fix(samples): fix non-working explit setup sample (#93)
  • doc: fix usage of logger.info in README.md (#83)
  • doc: fix link to HttpRequest message (#68)

Dependency updates

  • chore(deps): upgrade to @g-c/logging@3.0.1 (#126)
  • chore: pin to delay@3.0.x (#127)
  • chore(deps): update dependency execa to ^0.11.0 (#125)
  • chore(deps): update dependency eslint-config-prettier to v3 (#120)
  • chore(deps): update dependency pify to v4 (#119)
  • chore(deps): update dependency got to v9 (#114)
  • fix(deps): update dependency @opencensus/propagation-stackdriver to ^0.0.3 (#112)
  • chore(deps): update dependency typescript to v3 (#109)
  • chore(deps): update dependency eslint-plugin-node to v7 (#96)
  • chore(deps): update dependency gts to ^0.8.0 (#92)
  • fix(deps): update dependency @google-cloud/logging to v2 (#86)
  • fix(deps): update dependency yargs to v12 (#82)
  • chore: update dependencies (#81)
  • Configure Renovate (#74)
  • chore(package): missing @types/node dev dependency (#75)
  • chore: update all dependencies (#71)
  • chore(package): upgrade gts and typescript (#70)

Keepin' the lights on

  • chore: ignore package-lock.json (#118)
  • chore: update renovate config (#113)
  • remove that whitespace (#111)
  • chore: assert.deelEqual => assert.deepStrictEqual (#108)
  • chore: move mocha options to mocha.opts (#106)
  • chore: re-enable codecov && drop greenkeeper badge (#98)
  • refactor: drop repo-tool as an exec wrapper (#79)
  • chore: update sample lockfiles (#78)
  • fix: update linking for samples (#77)
  • cleanup: remove some casts (#76)
  • fix: the system tests use a custom log (#73)
  • test: use source-map-support (#72)
  • chore: remove --bail from the system tests config (#67)
  • chore: the ultimate fix for repo-tools EPERM (#64)