{"id":13598749,"url":"https://github.com/gremo/nest-winston","last_synced_at":"2025-05-13T22:02:37.234Z","repository":{"id":37926195,"uuid":"141901496","full_name":"gremo/nest-winston","owner":"gremo","description":"A Nest module wrapper form winston logger","archived":false,"fork":false,"pushed_at":"2025-05-12T23:34:35.000Z","size":32340,"stargazers_count":688,"open_issues_count":6,"forks_count":96,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-05-13T00:29:19.446Z","etag":null,"topics":["logger","nestjs","winston"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gremo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yaml","license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"gremo"}},"created_at":"2018-07-22T14:11:36.000Z","updated_at":"2025-05-08T03:18:57.000Z","dependencies_parsed_at":"2023-09-26T04:00:37.282Z","dependency_job_id":"a12451c5-fcf5-4708-91c2-6a4fe583300e","html_url":"https://github.com/gremo/nest-winston","commit_stats":{"total_commits":635,"total_committers":27,"mean_commits":23.51851851851852,"dds":0.4283464566929134,"last_synced_commit":"5bea16f676809d445135f1498700a35b32804b8a"},"previous_names":[],"tags_count":41,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gremo%2Fnest-winston","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gremo%2Fnest-winston/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gremo%2Fnest-winston/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gremo%2Fnest-winston/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gremo","download_url":"https://codeload.github.com/gremo/nest-winston/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254036808,"owners_count":22003652,"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":["logger","nestjs","winston"],"created_at":"2024-08-01T17:00:55.799Z","updated_at":"2025-05-13T22:02:37.196Z","avatar_url":"https://github.com/gremo.png","language":"TypeScript","funding_links":["https://github.com/sponsors/gremo"],"categories":["Components \u0026 Libraries","资源","TypeScript"],"sub_categories":["组件和库"],"readme":"\u003cp align=\"center\"\u003e\n  \u003ca href=\"http://nestjs.com\"\u003e\u003cimg alt=\"Nest Logo\" src=\"https://nestjs.com/img/logo-small.svg\" width=\"120\"\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n\u003ch1 align=\"center\"\u003e\n  nest-winston\n\u003c/h1\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://www.npmjs.com/package/nest-winston\"\u003e\u003cimg alt=\"NPM version\" src=\"https://img.shields.io/npm/v/nest-winston.svg\"\u003e\u003c/a\u003e\n  \u003ca href=\"https://www.npmjs.com/package/nest-winston\"\u003e\u003cimg alt=\"NPM downloads\" src=\"https://img.shields.io/npm/dw/nest-winston.svg\"\u003e\u003c/a\u003e\n  \u003ca href=\"https://github.com/gremo/nest-winston/pulse\"\u003e\u003cimg src=\"https://img.shields.io/github/commit-activity/m/gremo/nest-winston\" alt=\"GitHub commit activity\"\u003e\u003c/a\u003e\n  \u003ca href=\"https://github.com/gremo/nest-winston/graphs/contributors\"\u003e\u003cimg src=\"https://img.shields.io/github/contributors/gremo/nest-winston\" alt=\"Contributors\"\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cimg alt=\"GitHub last commit\" src=\"https://img.shields.io/github/last-commit/gremo/nest-winston\"\u003e\n  \u003cimg alt=\"GitHub Workflow Status\" src=\"https://img.shields.io/github/actions/workflow/status/gremo/nest-winston/ci.yaml\"\u003e\n  \u003ca href=\"https://github.com/gremo/nest-winston/issues\"\u003e\u003cimg alt=\"GitHub issues\" src=\"https://img.shields.io/github/issues/gremo/nest-winston.svg\"\u003e\u003c/a\u003e\n  \u003ca href=\"https://github.com/gremo/nest-winston/pulls\"\u003e\u003cimg alt=\"GitHub pull requests\" src=\"https://img.shields.io/github/issues-pr/gremo/nest-winston\"\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  A \u003ca href=\"https://github.com/nestjs/nest\"\u003eNest\u003c/a\u003e module wrapper for \u003ca href=\"https://github.com/winstonjs/winston\"\u003ewinston\u003c/a\u003e logger.\n\u003c/p\u003e\n\n\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\n\u003c!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --\u003e\n**Table of Contents**\n\n- [Installation](#installation)\n- [Quick start](#quick-start)\n- [Async configuration](#async-configuration)\n- [Replacing the Nest logger](#replacing-the-nest-logger)\n- [Replacing the Nest logger (also for bootstrapping)](#replacing-the-nest-logger-also-for-bootstrapping)\n- [Injection and usage summary](#injection-and-usage-summary)\n- [Utilities](#utilities)\n- [Logger methods](#logger-methods)\n- [Upgrade](#upgrade)\n- [Contributing](#contributing)\n- [License](#license)\n\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\n\n## Installation\n\n```bash\nnpm install --save nest-winston winston\n```\n\nHaving troubles configuring `nest-winston`? Clone this repository and `cd` in a sample:\n\n```bash\ncd sample/quick-start\nnpm install\nnpm run start:dev\n```\n\nIf you want to upgrade to a major or minor version, have a look at the [upgrade](#upgrade) section.\n\n## Quick start\n\nImport `WinstonModule` into the root `AppModule` and use the `forRoot()` method to configure it. This method accepts the same options object as [`createLogger()`](https://github.com/winstonjs/winston#usage) function from the winston package:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { WinstonModule } from 'nest-winston';\nimport * as winston from 'winston';\n\n@Module({\n  imports: [\n    WinstonModule.forRoot({\n      // options\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nAfterward, the winston instance will be available to inject across entire project (and in your feature modules, being `WinstonModule` a global one) using the `WINSTON_MODULE_PROVIDER` injection token:\n\n```typescript\nimport { Controller, Inject } from '@nestjs/common';\nimport { WINSTON_MODULE_PROVIDER } from 'nest-winston';\nimport { Logger } from 'winston';\n\n@Controller('cats')\nexport class CatsController {\n  constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger) { }\n}\n```\n\n## Async configuration\n\n\u003e **Caveats**: because the way Nest works, you can't inject dependencies exported from the root module itself (using `exports`). If you use `forRootAsync()` and need to inject a service, that service must be either imported using the `imports` options or exported from a [global module](https://docs.nestjs.com/modules#global-modules).\n\nMaybe you need to asynchronously pass your module options, for example when you need a configuration service. In such case, use the `forRootAsync()` method, returning an options object from the `useFactory` method:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { WinstonModule } from 'nest-winston';\nimport * as winston from 'winston';\n\n@Module({\n  imports: [\n    WinstonModule.forRootAsync({\n      useFactory: () =\u003e ({\n        // options\n      }),\n      inject: [],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nThe factory might be async, can inject dependencies with `inject` option and import other modules using the `imports` option.\n\nAlternatively, you can use the `useClass` syntax:\n\n```typescript\nWinstonModule.forRootAsync({\n  useClass: WinstonConfigService,\n})\n```\n\nWith the above code, Nest will create a new instance of `WinstonConfigService` and its method `createWinstonModuleOptions` will be called in order to provide the module options.\n\n## Replacing the Nest logger\n\nThis module also provides the `WinstonLogger` class (custom implementation of the [`LoggerService`](https://github.com/nestjs/nest/blob/main/packages/common/services/logger.service.ts#L10) interface) to be used by Nest for system logging. This will ensure consistent behavior and formatting across both Nest system logging and your application event/message logging.\n\nChange your `main.ts` as shown below:\n\n```typescript\nimport { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));\n  await app.listen(3000);\n}\nbootstrap();\n```\n\nThen inject the logger using the `WINSTON_MODULE_NEST_PROVIDER` token and the `LoggerService` typing:\n\n```typescript\nimport { Controller, Inject, LoggerService } from '@nestjs/common';\nimport { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';\n\n@Controller('cats')\nexport class CatsController {\n  constructor(@Inject(WINSTON_MODULE_NEST_PROVIDER) private readonly logger: LoggerService) { }\n}\n```\n\nUnder the hood, the `WinstonLogger` class uses the configured winston logger instance (through `forRoot` or `forRootAsync`), forwarding all calls to it.\n\n## Replacing the Nest logger (also for bootstrapping)\n\n\u003e **Important**: by doing this, you give up the dependency injection, meaning that `forRoot` and `forRootAsync` are not needed and shouldn't be used. Remove them from your main module.\n\nUsing the dependency injection has one minor drawback. Nest has to bootstrap the application first (instantiating modules and providers, injecting dependencies, etc.) and during this process the instance of `WinstonLogger` is not yet available, which means that Nest falls back to the internal logger.\n\nOne solution is to create the logger outside of the application lifecycle, using the `createLogger` function, and pass it to `NestFactory.create`. Nest will then wrap our winston logger (the same instance returned by the `createLogger` method) into the `Logger` class, forwarding all calls to it:\n\n```typescript\nimport { WinstonModule } from 'nest-winston';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule, {\n    logger: WinstonModule.createLogger({\n      // options (same as WinstonModule.forRoot() options)\n    })\n  });\n  await app.listen(3000);\n}\nbootstrap();\n```\n\nAn alternative is to provide directly an instance of Winston in the options. This allows you to keep a reference to the instance and interact with it.\n\n```typescript\nimport { createLogger } from 'winston';\nimport { WinstonModule } from 'nest-winston';\n\nasync function bootstrap() {\n  // createLogger of Winston\n  const instance = createLogger({\n    // options of Winston\n  });\n  const app = await NestFactory.create(AppModule, {\n    logger: WinstonModule.createLogger({\n      instance,\n    }),\n  });\n  await app.listen(3000);\n}\nbootstrap();\n```\n\nThe usage afterwards for both solutions is the same. First, change your main module to provide the `Logger` service:\n\n```typescript\nimport { Logger, Module } from '@nestjs/common';\n\n@Module({\n  providers: [Logger],\n})\nexport class AppModule {}\n```\n\nThen inject the logger simply by type hinting it with `Logger` from `@nestjs/common`:\n\n```typescript\nimport { Controller, Logger } from '@nestjs/common';\n\n@Controller('cats')\nexport class CatsController {\n  constructor(private readonly logger: Logger) {}\n}\n```\n\nAlternative syntax using the `LoggerService` typing and the `@Inject` decorator:\n\n```typescript\nimport { Controller, Inject, Logger, LoggerService } from '@nestjs/common';\n\n@Controller('cats')\nexport class CatsController {\n  constructor(@Inject(Logger) private readonly logger: LoggerService) {}\n}\n```\n\n## Injection and usage summary\n\nHere is a summary of the three techniques explained above:\n\n| Injection token                | Typing                                | Module config | Usage                                                                  |\n| :----------------------------- | :------------------------------------ | :------------ | :--------------------------------------------------------------------- |\n| `WINSTON_MODULE_PROVIDER`      | `Logger` from `winston`               | Yes           | + Your application/message logging |\n| `WINSTON_MODULE_NEST_PROVIDER` | `LoggerService` from `@nestjs/common` | Yes           | + Your application/message logging \u003cbr\u003e + Nest logger |\n| *none*                         | `Logger` from `@nestjs/common`        | No            | + Your application/message logging \u003cbr\u003e + Nest logger \u003cbr\u003e + Application bootstrapping |\n\n## Utilities\n\nThe module also provides a custom Nest-like special formatter for console transports named `nestLike`. Supported options:\n\n- `colors`: enable console colors, defaults to `true`, unless `process.env.NO_COLOR` is set (same behaviour of Nest \u003e 7.x)\n- `prettyPrint`: pretty format log metadata, defaults to `true`\n- `processId`: includes the Node Process ID (`process.pid`) in the output, defaults to `true`\n- `appName`: includes the provided application name in the output, defaults to `true`\n\nNote: When providing partial options, unspecified options will retain their default values.\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { utilities as nestWinstonModuleUtilities, WinstonModule } from 'nest-winston';\nimport * as winston from 'winston';\n\n@Module({\n  imports: [\n    WinstonModule.forRoot({\n      transports: [\n        new winston.transports.Console({\n          format: winston.format.combine(\n            winston.format.timestamp(),\n            winston.format.ms(),\n            nestWinstonModuleUtilities.format.nestLike('MyApp', {\n              colors: true,\n              prettyPrint: true,\n              processId: true,\n              appName: true,\n            }),\n          ),\n        }),\n        // other transports...\n      ],\n      // other options\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n## Logger methods\n\n\u003e **Note**: the logger instance has different logger methods, and each takes different arguments. To make sure the logger is being formatted the same way across the board take note of the following:\n\n```typescript\ndebug(message: any, context?: string)\nlog(message: any, context?: string)\nerror(message: any, stack?: string, context?: string)\nfatal(message: any, stack?: string, context?: string)\nverbose(message: any, context?: string)\nwarn(message: any, context?: string)\n```\n\nExample:\n\n```typescript\nimport { Controller, Get, Logger } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n  constructor(\n    private readonly appService: AppService,\n    private readonly logger: Logger,\n  ) {}\n\n  @Get()\n  getHello(): string {\n    this.logger.log('Calling getHello()', AppController.name);\n    this.logger.debug('Calling getHello()', AppController.name);\n    this.logger.verbose('Calling getHello()', AppController.name);\n    this.logger.warn('Calling getHello()', AppController.name);\n\n    try {\n      throw new Error()\n    } catch (e) {\n      this.logger.error('Calling getHello()', e.stack, AppController.name);\n    }\n\n    return this.appService.getHello();\n  }\n}\n```\n\n## Upgrade\n\nSome notes about upgrading to a major or minor version.\n\n### 1.6.x to 1.7\n\n- The exported type `NestLikeConsoleFormatOptions` has slightly changed: `prettyPrint` is now optional and `colors` has been added.\n- The `nestLike` formatter has the new `colors` option: if not provided, colors will be used according to Nest \"approach\" (disabled if env variable `process.env.NO_COLOR` is defined). Before output was always colorized.\n\n## Contributing\n\nAll types of contributions are encouraged and valued. See the [Contributing](.github/CONTRIBUTING.md) guidelines, the community looks forward to your contributions!\n\n[![Contributors list](https://raw.githubusercontent.com/gremo/nest-winston/main/contributors.svg)](https://github.com/gremo/nest-winston/graphs/contributors)\n\n## License\n\nThis project is released under the under terms of the [ISC License](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgremo%2Fnest-winston","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgremo%2Fnest-winston","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgremo%2Fnest-winston/lists"}