{"id":18533089,"url":"https://github.com/googleapis/nodejs-logging-bunyan","last_synced_at":"2025-04-07T23:13:02.088Z","repository":{"id":26416692,"uuid":"98464530","full_name":"googleapis/nodejs-logging-bunyan","owner":"googleapis","description":"Node.js client integration between Stackdriver Logging and Bunyan.","archived":false,"fork":false,"pushed_at":"2025-03-26T20:13:18.000Z","size":2018,"stargazers_count":62,"open_issues_count":14,"forks_count":34,"subscribers_count":46,"default_branch":"main","last_synced_at":"2025-03-31T22:22:12.732Z","etag":null,"topics":["bunyan","logging","nodejs","stackdriver"],"latest_commit_sha":null,"homepage":"https://cloud.google.com/logging/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/googleapis.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-07-26T20:47:06.000Z","updated_at":"2025-01-13T01:54:48.000Z","dependencies_parsed_at":"2023-11-15T18:29:39.051Z","dependency_job_id":"fd52dcce-dc05-493a-ab96-c565969ebb4d","html_url":"https://github.com/googleapis/nodejs-logging-bunyan","commit_stats":{"total_commits":527,"total_committers":45,"mean_commits":11.71111111111111,"dds":0.8709677419354839,"last_synced_commit":"34a278c724f9bfcf1511e22b7deb234007f713bf"},"previous_names":[],"tags_count":54,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fnodejs-logging-bunyan","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fnodejs-logging-bunyan/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fnodejs-logging-bunyan/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fnodejs-logging-bunyan/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/googleapis","download_url":"https://codeload.github.com/googleapis/nodejs-logging-bunyan/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247744335,"owners_count":20988783,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bunyan","logging","nodejs","stackdriver"],"created_at":"2024-11-06T19:09:12.835Z","updated_at":"2025-04-07T23:13:02.071Z","avatar_url":"https://github.com/googleapis.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[//]: # \"This README.md file is auto-generated, all changes to this file will be lost.\"\n[//]: # \"To regenerate it, use `python -m synthtool`.\"\n\u003cimg src=\"https://avatars2.githubusercontent.com/u/2810941?v=3\u0026s=96\" alt=\"Google Cloud Platform logo\" title=\"Google Cloud Platform\" align=\"right\" height=\"96\" width=\"96\"/\u003e\n\n# [Cloud Logging for Bunyan: Node.js Client](https://github.com/googleapis/nodejs-logging-bunyan)\n\n[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages)\n[![npm version](https://img.shields.io/npm/v/@google-cloud/logging-bunyan.svg)](https://www.npmjs.org/package/@google-cloud/logging-bunyan)\n\n\n\n\nThis module provides an easy to use, higher-level layer for working with [Cloud Logging](https://cloud.google.com/logging/docs),\ncompatible with [Bunyan](https://www.npmjs.com/package/bunyan). Simply attach this as a transport to your existing Bunyan loggers.\n\n\nA comprehensive list of changes in each version may be found in\n[the CHANGELOG](https://github.com/googleapis/nodejs-logging-bunyan/blob/main/CHANGELOG.md).\n\n* [Cloud Logging for Bunyan Node.js Client API Reference][client-docs]\n* [Cloud Logging for Bunyan Documentation][product-docs]\n* [github.com/googleapis/nodejs-logging-bunyan](https://github.com/googleapis/nodejs-logging-bunyan)\n\nRead more about the client libraries for Cloud APIs, including the older\nGoogle APIs Client Libraries, in [Client Libraries Explained][explained].\n\n[explained]: https://cloud.google.com/apis/docs/client-libraries-explained\n\n**Table of contents:**\n\n\n* [Quickstart](#quickstart)\n  * [Before you begin](#before-you-begin)\n  * [Installing the client library](#installing-the-client-library)\n  * [Using the client library](#using-the-client-library)\n* [Samples](#samples)\n* [Versioning](#versioning)\n* [Contributing](#contributing)\n* [License](#license)\n\n## Quickstart\n\n### Before you begin\n\n1.  [Select or create a Cloud Platform project][projects].\n1.  [Enable the Cloud Logging for Bunyan API][enable_api].\n1.  [Set up authentication][auth] so you can access the\n    API from your local workstation.\n\n### Installing the client library\n\n```bash\nnpm install @google-cloud/logging-bunyan\n```\n\n\n### Using the client library\n\n```javascript\nconst bunyan = require('bunyan');\n\n// Imports the Google Cloud client library for Bunyan\nconst {LoggingBunyan} = require('@google-cloud/logging-bunyan');\n\n// Creates a Bunyan Cloud Logging client\nconst loggingBunyan = new LoggingBunyan();\n\n// Create a Bunyan logger that streams to Cloud Logging\n// Logs will be written to: \"projects/YOUR_PROJECT_ID/logs/bunyan_log\"\nconst logger = bunyan.createLogger({\n  // The JSON payload of the log as it appears in Cloud Logging\n  // will contain \"name\": \"my-service\"\n  name: 'my-service',\n  streams: [\n    // Log to the console at 'info' and above\n    {stream: process.stdout, level: 'info'},\n    // And log to Cloud Logging, logging at 'info' and above\n    loggingBunyan.stream('info'),\n  ],\n});\n\n// Writes some log entries\nlogger.error('warp nacelles offline');\nlogger.info('shields at 99%');\n\n```\n### Using as an express middleware\n\n***NOTE: this feature is experimental. The API may change in a backwards\nincompatible way until this is deemed stable. Please provide us feedback so\nthat we can better refine this express integration.***\n\nWe provide a middleware that can be used in an express application. Apart from\nbeing easy to use, this enables some more powerful features of Cloud\nLogging: request bundling. Any application logs emitted on behalf of a specific\nrequest will be shown nested inside the request log as you see in this\nscreenshot:\n\n![Request Bundling Example](https://raw.githubusercontent.com/googleapis/nodejs-logging-bunyan/master/doc/images/request-bundling.png)\n\nThe middleware adds a `bunyan`-style log function to the `request` object. You\ncan use this wherever you have access to the `request` object (`req` in the\nsample below). All log entries that are made on behalf of a specific request are\nshown bundled together in the Cloud Logging UI.\n\n```javascript\nconst lb = require('@google-cloud/logging-bunyan');\n\n// Import express module and create an http server.\nconst express = require('express');\n\nasync function startServer() {\n  const {logger, mw} = await lb.express.middleware();\n  const app = express();\n\n  // Install the logging middleware. This ensures that a Bunyan-style `log`\n  // function is available on the `request` object. Attach this as one of the\n  // earliest middleware to make sure that log function is available in all the\n  // subsequent middleware and routes.\n  app.use(mw);\n\n  // Setup an http route and a route handler.\n  app.get('/', (req, res) =\u003e {\n    // `req.log` can be used as a bunyan style log method. All logs generated\n    // using `req.log` use the current request context. That is, all logs\n    // corresponding to a specific request will be bundled in the Cloud UI.\n    req.log.info('this is an info log message');\n    res.send('hello world');\n  });\n\n  // `logger` can be used as a global logger, one not correlated to any specific\n  // request.\n  logger.info({port: 8080}, 'bonjour');\n\n  // Start listening on the http server.\n  app.listen(8080, () =\u003e {\n    console.log('http server listening on port 8080');\n  });\n}\n\nstartServer();\n```\n\n### Error Reporting\n\nAny `Error` objects you log at severity `error` or higher can automatically be picked up by [Cloud Error Reporting](https://cloud.google.com/error-reporting/) if you have specified a `serviceContext.service` when instantiating a `LoggingBunyan` instance:\n\n```javascript\nconst loggingBunyan = new LoggingBunyan({\n  serviceContext: {\n    service: 'my-service', // required to report logged errors\n                           // to the Google Cloud Error Reporting\n                           // console\n    version: 'my-version'\n  }\n});\n```\n\nIt is an error to specify a `serviceContext` but not specify `serviceContext.service`.\n\nMake sure to add logs to your [uncaught exception](https://nodejs.org/api/process.html#process_event_uncaughtexception) and [unhandled rejection](https://nodejs.org/api/process.html#process_event_unhandledrejection) handlers if you want to see those errors too.\n\nYou may also want to see the [@google-cloud/error-reporting][@google-cloud/error-reporting] module which provides direct access to the Error Reporting API.\n\n### Special Payload Fields in LogEntry\n\nThere 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](https://cloud.google.com/logging/docs/structured-logging#special-payload-fields) will be used to set the corresponding fields in the `LogEntry`. Please be aware of these special fields to avoid unexpected logging behavior. \n\n### LogEntry Labels\n\nIf the bunyan log record contains a label property where all the values are strings, we automatically promote that\nproperty to be the [`LogEntry.labels`](https://cloud.google.com/logging/docs/reference/v2/rpc/google.logging.v2#logentry) value rather\nthan being one of the properties in the `payload` fields. This makes it easier to filter the logs in the UI using the labels.\n\n```javascript\nlogger.info({labels: {someKey: 'some value'}}, 'test log message');\n```\n\nAll the label values must be strings for this automatic promotion to work. Otherwise the labels are left in the payload.\n\n### Formatting Request Logs\n\nTo 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`](https://cloud.google.com/logging/docs/reference/v2/rpc/google.logging.type#google.logging.type.HttpRequest) message and Cloud logging will show this as a request log. Example:\n\n![Request Log Example](https://raw.githubusercontent.com/googleapis/nodejs-logging-bunyan/master/doc/images/request-log.png)\n\n```js\nlogger.info({\n  httpRequest: {\n    status: res.statusCode,\n    requestUrl: req.url,\n    requestMethod: req.method,\n    remoteIp: req.connection.remoteAddress,\n    // etc.\n  }\n}, req.path);\n```\n\nThe `httpRequest` property must be a properly formatted [`HttpRequest`](https://cloud.google.com/logging/docs/reference/v2/rpc/google.logging.type#google.logging.type.HttpRequest) message. (Note: the linked protobuf documentation shows `snake_case` property names, but in JavaScript one needs to provide property names in `camelCase`.)\n\n### Correlating Logs with Traces\n\nIf 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:\n\n![Logs in Trace Example](https://raw.githubusercontent.com/googleapis/nodejs-logging-bunyan/master/doc/images/bunyan-logs-in-trace.png)\n\nIf 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:\n\n```js\nconst bunyan = require('bunyan');\n// Node 6+\nconst {LoggingBunyan, LOGGING_TRACE_KEY} = require('@google-cloud/logging-bunyan');\nconst loggingBunyan = LoggingBunyan();\n\n...\n\nlogger.info({\n  [LOGGING_TRACE_KEY]: 'custom-trace-value'\n}, 'Bunyan log entry with custom trace field');\n```\n\n### Error handling with a default callback\nThe `LoggingBunyan` class creates an instance of `Logging` which creates the `Log` class from `@google-cloud/logging` package to write log entries. \nThe `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.\nIf the error is not handled, it could crash the application. One possible way to handle the error is to provide a default callback\nto the `LoggingBunyan` constructor which will be used to initialize the `Log` object with that callback like in the example below:\n\n```js\n// Imports the Google Cloud client library for Bunyan\nconst {LoggingBunyan} = require('@google-cloud/logging-bunyan');\n// Creates a client\nconst loggingBunyan = new LoggingBunyan({\n  projectId: 'your-project-id',\n  keyFilename: '/path/to/key.json',\n  defaultCallback: err =\u003e {\n      if (err) {\n      console.log('Error occured: ' + err);\n      }\n  },\n});\n```\n\n### Alternative way to ingest logs in Google Cloud managed environments\nIf you use this library with the Cloud Logging Agent, you can configure the handler to output logs to `process.stdout` using\nthe [structured logging Json format](https://cloud.google.com/logging/docs/structured-logging#special-payload-fields).\nTo do this, add `redirectToStdout: true` parameter to the `LoggingBunyan` constructor as in sample below.\nYou can use this parameter when running applications in Google Cloud managed environments such as AppEngine, Cloud Run,\nCloud Function or GKE. The logger agent installed on these environments can capture `process.stdout` and ingest it into Cloud Logging.\nThe agent can parse structured logs printed to `process.stdout` and capture additional log metadata beside the log payload.\nIt is recommended to set `redirectToStdout: true` in serverless environments like Cloud Functions since it could \ndecrease logging record loss upon execution termination - since all logs are written to `process.stdout` those\nwould be picked up by the Cloud Logging Agent running in Google Cloud managed environment. \nNote that there is also a `useMessageField` option which controls if \"message\" field is used to store \nstructured, non-text data inside `jsonPayload` field when `redirectToStdout` is set. By default `useMessageField` is always `true`.\nSet the `skipParentEntryForCloudRun` option to skip creating an entry for the request itself as Cloud Run already automatically creates\nsuch log entries. This might become the default behaviour in a next major version.\n\n```js\n// Imports the Google Cloud client library for Bunyan\nconst {LoggingBunyan} = require('@google-cloud/logging-bunyan');\n\n// Creates a client\nconst loggingBunyan = new LoggingBunyan({\n  projectId: 'your-project-id',\n  keyFilename: '/path/to/key.json',\n  redirectToStdout: true,\n});\n```\n\n\n## Samples\n\nSamples are in the [`samples/`](https://github.com/googleapis/nodejs-logging-bunyan/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample.\n\n| Sample                      | Source Code                       | Try it |\n| --------------------------- | --------------------------------- | ------ |\n| Express | [source code](https://github.com/googleapis/nodejs-logging-bunyan/blob/main/samples/express.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-logging-bunyan\u0026page=editor\u0026open_in_editor=samples/express.js,samples/README.md) |\n| Quickstart | [source code](https://github.com/googleapis/nodejs-logging-bunyan/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-logging-bunyan\u0026page=editor\u0026open_in_editor=samples/quickstart.js,samples/README.md) |\n| Explict Auth Setup | [source code](https://github.com/googleapis/nodejs-logging-bunyan/blob/main/samples/setup_explicit.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-logging-bunyan\u0026page=editor\u0026open_in_editor=samples/setup_explicit.js,samples/README.md) |\n\n\n\nThe [Cloud Logging for Bunyan Node.js Client API Reference][client-docs] documentation\nalso contains samples.\n\n## Supported Node.js Versions\n\nOur client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule).\nLibraries are compatible with all current _active_ and _maintenance_ versions of\nNode.js.\nIf you are using an end-of-life version of Node.js, we recommend that you update\nas soon as possible to an actively supported LTS version.\n\nGoogle's client libraries support legacy versions of Node.js runtimes on a\nbest-efforts basis with the following warnings:\n\n* Legacy versions are not tested in continuous integration.\n* Some security patches and features cannot be backported.\n* Dependencies cannot be kept up-to-date.\n\nClient libraries targeting some end-of-life versions of Node.js are available, and\ncan be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag).\nThe dist-tags follow the naming convention `legacy-(version)`.\nFor example, `npm install @google-cloud/logging-bunyan@legacy-8` installs client libraries\nfor versions compatible with Node.js 8.\n\n## Versioning\n\nThis library follows [Semantic Versioning](http://semver.org/).\n\n\n\nThis library is considered to be **stable**. The code surface will not change in backwards-incompatible ways\nunless absolutely necessary (e.g. because of critical security issues) or with\nan extensive deprecation period. Issues and requests against **stable** libraries\nare addressed with the highest priority.\n\n\n\n\n\n\nMore Information: [Google Cloud Platform Launch Stages][launch_stages]\n\n[launch_stages]: https://cloud.google.com/terms/launch-stages\n\n## Contributing\n\nContributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-logging-bunyan/blob/main/CONTRIBUTING.md).\n\nPlease note that this `README.md`, the `samples/README.md`,\nand a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`)\nare generated from a central template. To edit one of these files, make an edit\nto its templates in\n[directory](https://github.com/googleapis/synthtool).\n\n## License\n\nApache Version 2.0\n\nSee [LICENSE](https://github.com/googleapis/nodejs-logging-bunyan/blob/main/LICENSE)\n\n[client-docs]: https://cloud.google.com/nodejs/docs/reference/logging-bunyan/latest\n[product-docs]: https://cloud.google.com/logging\n[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png\n[projects]: https://console.cloud.google.com/project\n[billing]: https://support.google.com/cloud/answer/6293499#enable-billing\n[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=logging.googleapis.com\n[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogleapis%2Fnodejs-logging-bunyan","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgoogleapis%2Fnodejs-logging-bunyan","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogleapis%2Fnodejs-logging-bunyan/lists"}