{"id":18533308,"url":"https://github.com/googleapis/nodejs-logging-winston","last_synced_at":"2025-05-15T08:00:29.889Z","repository":{"id":38211146,"uuid":"98464590","full_name":"googleapis/nodejs-logging-winston","owner":"googleapis","description":"Node.js client integration between Stackdriver Logging and Winston.","archived":false,"fork":false,"pushed_at":"2025-05-13T18:20:10.000Z","size":2512,"stargazers_count":111,"open_issues_count":28,"forks_count":50,"subscribers_count":50,"default_branch":"main","last_synced_at":"2025-05-13T19:37:05.493Z","etag":null,"topics":["logging","nodejs","stackdriver","winston"],"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,"zenodo":null}},"created_at":"2017-07-26T20:47:48.000Z","updated_at":"2025-05-13T18:20:03.000Z","dependencies_parsed_at":"2023-02-01T17:31:24.865Z","dependency_job_id":"cf88916e-e5e1-4362-9f9f-e3c67358fd6a","html_url":"https://github.com/googleapis/nodejs-logging-winston","commit_stats":{"total_commits":569,"total_committers":58,"mean_commits":9.810344827586206,"dds":0.8910369068541301,"last_synced_commit":"47c9f98bb70595404a4e30e8a76f7f0c09004190"},"previous_names":[],"tags_count":64,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fnodejs-logging-winston","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fnodejs-logging-winston/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fnodejs-logging-winston/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fnodejs-logging-winston/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/googleapis","download_url":"https://codeload.github.com/googleapis/nodejs-logging-winston/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254050919,"owners_count":22006383,"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":["logging","nodejs","stackdriver","winston"],"created_at":"2024-11-06T19:10:56.147Z","updated_at":"2025-05-15T08:00:29.833Z","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 Winston: Node.js Client](https://github.com/googleapis/nodejs-logging-winston)\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-winston.svg)](https://www.npmjs.org/package/@google-cloud/logging-winston)\n\n\n\n\nThis module provides a higher-level layer for working with\n[Cloud Logging](https://cloud.google.com/logging/docs), compatible with\n[Winston](https://www.npmjs.com/package/winston). Simply attach this as a\ntransport to your existing Winston loggers.\n\n\nA comprehensive list of changes in each version may be found in\n[the CHANGELOG](https://github.com/googleapis/nodejs-logging-winston/blob/main/CHANGELOG.md).\n\n* [Cloud Logging for Winston Node.js Client API Reference][client-docs]\n* [Cloud Logging for Winston Documentation][product-docs]\n* [github.com/googleapis/nodejs-logging-winston](https://github.com/googleapis/nodejs-logging-winston)\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 Winston 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-winston\n```\n\n\n### Using the client library\n\n```javascript\nconst winston = require('winston');\n\n// Imports the Google Cloud client library for Winston\nconst {LoggingWinston} = require('@google-cloud/logging-winston');\n\nconst loggingWinston = new LoggingWinston();\n\n// Create a Winston logger that streams to Cloud Logging\n// Logs will be written to: \"projects/YOUR_PROJECT_ID/logs/winston_log\"\nconst logger = winston.createLogger({\n  level: 'info',\n  transports: [\n    new winston.transports.Console(),\n    // Add Cloud Logging\n    loggingWinston,\n  ],\n});\n\n// Writes some log entries\nlogger.error('warp nacelles offline');\nlogger.info('shields at 99%');\n\n```\nFor a more detailed Cloud Logging setup guide, see https://cloud.google.com/logging/docs/setup/nodejs.\n\nCreates a Winston logger that streams to Cloud Logging\n\nLogs will be written to: \"projects/YOUR_PROJECT_ID/logs/winston_log\"\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-winston/master/doc/images/request-bundling.png)\n\nThis middleware adds a `winston`-style log function to the `request` object.\nYou can 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 lw = require('@google-cloud/logging-winston');\nconst winston = require('winston');\n\n// Import express module and create an http server.\nconst express = require('express');\nconst logger = winston.createLogger();\n\nasync function main() {\n    // Create a middleware that will use the provided logger.\n    // A Cloud Logging transport will be created automatically\n    // and added onto the provided logger.\n    const mw = await lw.express.makeMiddleware(logger);\n    // Alternatively, you can construct a LoggingWinston transport\n    // yourself and pass it int.\n    // const transport = new LoggingWinston({...});\n    // const mw = await lw.express.makeMiddleware(logger, transport);\n\n    const app = express();\n\n    // Install the logging middleware. This ensures that a Winston-style `log`\n    // function is available on the `request` object. Attach this as one of the\n    // earliest middleware to make sure that the log function is available in all\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 winston 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 Logging\n        // 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('bonjour');\n\n    // Start listening on the http server.\n    app.listen(8080, () =\u003e {\n        logger.info('http server listening on port 8080');\n    });\n}\n\nmain();\n```\n\n### Error Reporting\n\nAny `Error` objects you log at severity `error` or higher can automatically be picked up by [Error Reporting](https://cloud.google.com/error-reporting/) if you have specified a `serviceContext.service` when instantiating a `LoggingWinston` instance:\n\n```javascript\nconst loggingWinston = new LoggingWinston({\nserviceContext: {\n    service: 'my-service', // required to report logged errors\n                        // to the 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](https://github.com/googleapis/nodejs-error-reporting) module which provides direct access to the Error Reporting API.\n\n### Error handling with a default callback\n\nThe `LoggingWinston` class creates an instance of `LoggingCommon` which by default uses 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 and an error is \nthrown - if error is not handled properly, it could crash the application. One possible way to handle the error is to provide a default callback\nto the `LoggingWinston` constructor which will be used to initialize `Log` object with that callback like in example below:\n\n```js\n// Imports the Google Cloud client library for Winston\nconst {LoggingWinston} = require('@google-cloud/logging-winston');\n\n// Creates a client\nconst loggingWinston = new LoggingWinston({\nprojectId: 'your-project-id',\nkeyFilename: '/path/to/key.json',\ndefaultCallback: err =\u003e {\n    if (err) {\n    console.log('Error occured: ' + err);\n    }\n},\n});\n```\n\n### Formatting Request Logs\n\n**NOTE: The express middleware provided by this library handles this automatically for you. These instructions are for there case where you may want to handle this manually.**\n\nTo format your request logs you can provide a `httpRequest` property as part of the log metadata you provide to winston. 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-winston/master/doc/images/request-log.png)\n\n```js\nwinston.info(`${req.url} endpoint hit`, {\nhttpRequest: {\n    status: res.statusCode,\n    requestUrl: req.url,\n    requestMethod: req.method,\n    remoteIp: req.connection.remoteAddress,\n    // etc.\n}\n});\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.\n\n**NOTE: Due to a bug in [logform](https://github.com/winstonjs/logform/issues/125) some built in Winston formatters might not work properly with `LoggingWinston`. For more information about the problem and possible workaround please see [540](https://github.com/googleapis/nodejs-logging-winston/issues/540). In addition, [Cloud Logging for Bunyan](https://github.com/googleapis/nodejs-logging-bunyan) could be considered as alternative.\n\n### Correlating Logs with Traces\n\n**NOTE: The express middleware provided by this library handles this automatically for you. These instructions are for there case where you may want to handle this manually.**\n\nIf you use [@google-cloud/trace-agent](https://www.npmjs.com/package/@google-cloud/trace-agent) module, then this module will set the Cloud Logging [LogEntry](https://cloud.google.com/logging/docs/reference/v2/rpc/google.logging.v2#logentry) `trace` property based on the current trace context when available. That correlation allows you to [view log entries](https://cloud.google.com/trace/docs/viewing-details#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-winston/master/doc/images/winston-logs-in-trace.png)\n\nIf you wish to set the LogEntry `trace`, `spanId`, and `traceSampled` properties with custom values, then set Winston metadata properties for `'logging.googleapis.com/trace'`, `'logging.googleapis.com/spanId'`, `'logging.googleapis.com/trace_sampled'`, which is exported by this module as `LOGGING_TRACE_KEY`, `LOGGING_SPAN_KEY`, and `LOGGING_SAMPLED_KEY` respectively. For example:\n\n```js\nconst winston = require('winston');\nconst {LoggingWinston} = require('@google-cloud/logging-winston');\n\n// ...\n\nwinston.info('Log entry with custom trace value', {\n[LoggingWinston.LOGGING_TRACE_KEY]: 'custom-trace-value'\n[LoggingWinston.LOGGING_SPAN_KEY]: 'custom-span-value'\n[LoggingWinston.LOGGING_SAMPLED_KEY]: true\n});\n```\n\n### Specifying default labels in the constructor\n\nYou can specify `labels` when initiating the logger constructor.\n\n```js\n// Creates a Winston Cloud Logging client\nconst loggingWinston = new LoggingWinston({\nlabels: {\n    name: 'some-name',\n    version: '0.1.0'\n}\n});\n\n// Writes some log entries\nlogger.debug('test msg');\n\n// you can also put some `labels` when calling the logger function\n// the `labels` will be merge together\nlogger.debug('test msg', {\nlabels: {\n    module: 'some-module'\n}\n});\n```\n\nThe `labels` will be on the Log Viewer.\n\n![Request log with labels](https://raw.githubusercontent.com/googleapis/nodejs-logging-winston/master/doc/images/request-log-with-labels.png)\n\n### Add a prefix to easily identify logs\n\nYou can specify a `prefix` in the constructor, and that `prefix` will be prepended to all logging messages. This can be helpful, for example, to quickly identify logs from different modules in a project.\n\n```js\n// Creates a Winston Cloud Logging client\nconst loggingWinston = new LoggingWinston({\nprefix: 'some-module'\n});\n\nlogger.debug('test msg');\n```\n\n![Request log with prefix](https://raw.githubusercontent.com/googleapis/nodejs-logging-winston/master/doc/images/request-log-with-prefix.png)\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 `LoggingWinston` 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 Winston\nconst {LoggingWinston} = require('@google-cloud/logging-winston');\n\n// Creates a client that writes logs to stdout\nconst loggingWinston = new LoggingWinston({\n  projectId: 'your-project-id',\n  keyFilename: '/path/to/key.json',\n  redirectToStdout: true,\n});\n```\n\n### Waiting for logs to be written\nStarting from v3.0, the [Winston](https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md#winstonlogger) library no longer supports\ncallbacks in their logging API, which reduces the ability to wait for logs to be written before exit/shutdown. The issue tracking the ask to reestablish callback support in Winston is tracked by [2095](https://github.com/winstonjs/winston/issues/2095).\nOne possible solution is to adopt an [Alternative way to ingest logs in Google Cloud managed environments](https://github.com/googleapis/nodejs-logging-winston#alternative-way-to-ingest-logs-in-google-cloud-managed-environments).\nAnother possible way is to use a `setTimeout` with a desired interval in order to let the library to send as many logs as possible.\n\n\n## Samples\n\nSamples are in the [`samples/`](https://github.com/googleapis/nodejs-logging-winston/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample.\n\n| Sample                      | Source Code                       | Try it |\n| --------------------------- | --------------------------------- | ------ |\n| Quickstart | [source code](https://github.com/googleapis/nodejs-logging-winston/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-winston\u0026page=editor\u0026open_in_editor=samples/quickstart.js,samples/README.md) |\n| Explicit Auth Setup | [source code](https://github.com/googleapis/nodejs-logging-winston/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-winston\u0026page=editor\u0026open_in_editor=samples/setup_explicit.js,samples/README.md) |\n\n\n\nThe [Cloud Logging for Winston 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-winston@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-winston/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-winston/blob/main/LICENSE)\n\n[client-docs]: https://cloud.google.com/nodejs/docs/reference/logging-winston/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-winston","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgoogleapis%2Fnodejs-logging-winston","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogleapis%2Fnodejs-logging-winston/lists"}