@dyihoon90/glogging

中文文档
4.0.5发布于 2026/06/02ISCTypeScriptCommonJS构建来源已验证近 30 天下载 4936

HTTP request logging middleware & transaction function decorator for express, using winston

原始使用文档
文档目录15 节
  1. Table of Content
  2. Installation
  3. Description
  4. GLogger
  5. Constructor
  6. Override default configs
  7. Instance methods
  8. Instance properties
  9. Express middlewares
  10. Class, Method & Function decorators for Express services (W…
  11. Purpose
  12. Metadata
  13. Decorators
  14. Examples
  15. Troubleshooting

Release pipeline CI pipeline

Audit logger for Express requests and Transactions

Table of Content

Installation

npm i @dyihoon90/glogging

Description

Glogger is a wrapper around the popular winston logging library.

This library provide convenience methods for the following use cases:

  1. Structured logging
  2. Logging request & response using Express middleware
  3. Logging using decorators in functions, class & class methods

By using this library in an Express server, you get:

BenefitsUsing?
Redaction of sensitive data in SG contextAutomatically redacts NRIC & sensitive info
Standardized log formatThe standard logger.info()
Standardized request & response logging for Express serversAdding the Glogger Express middlewares will automatically generate logs for incoming requests & outgoing responses
Unobtrusive logging for functions, class, & class methodDecorate functions & class methods using decorators will log the function invocation. Optionally it can also log what the function returns
Correlate function invocations in Express server using trxIdUse the enhanceReqWithTransactionAndTime in Middleware to add trxId to incoming request.
Pass the request object to as the first parameter in all decorated function & Glogger decorators will pick up the request context, such as the trxId.
Correlate requests across microservices using trxIdUse the enhanceReqWithTransactionAndTime in Middleware to add trxId to incoming request.
Pass this trxId to other Express servers that are using Glogger & they will output logs w the same trxId

GLogger

Construct an instance of a logger. Similar to how winston does it.

Constructor

const logger = new GLogger({ loggingMode: LoggingMode.LOCAL });

When constructing a logger instance, there are 3 modes for different environments

ModeDescription
LOCAL
  • defaults to have transport for console.
  • Log level up to debug
DEV
  • defaults to have transport for console.
  • Log level up to info
PRODUCTION
  • defaults to have no transport. Use glogger.addTransport to add a winston log transport.
  • Log level up to info

To override the default behaviors for each Mode above, you can use overrideDefault

const logger = new GLogger({
  loggingMode: LoggingMode.LOCAL,
  overrideDefault: { alwaysWriteToConsole: true, consoleLogSectionSeparator: '' }
});

Override default configs

ConfigPurpose
alwaysWriteToConsolealways write to console, regardless of environment. useful for AWS Lambda
consoleLogSectionSeparatoroverride the default section separator character for console logs. the default is newline '\n'. useful for AWS Lambda

Instance methods

MethodPurpose
debugcreate log object of level debug
infocreate log object of level info
warncreate log object of level warn
errorcreate log object of level error
toggleVerboseModeOntoggle debug mode to see what is being sent to the above log methods
addLogTransportadd a winston log transport to transport the log object

Instance properties

PropertyPurpose
winstonLoggerExpose the underlying winston logger object

Express middlewares

This library exports the following express middlewares. See the middlware examples for how to place these middleware in your Express server

MiddlewarePurpose
enhanceReqWithTransactionAndTimeenhance request with req.reqStartTimeInEpochMillis & req.uuid (if req.uuid does not already exist)
responseErrorLoggerFactoryfactory to create an error logger middleware. Error logger middleware does a logger.warn when it receives an error object from the previous middleware
responseSuccessLoggerFactoryfactory to create a successs logger middleware. Success logger middleware does a logger.info when the response status code is < 400

Express middleware will log all incoming request and outgoing response of your Express server with the following metadata:

MetadataFull NameWhat is it?Example
trxIdTransaction IDA randomly generated uuidv4 added to the express request by the enhanceReqWithTransactionAndTime middleware. If using multiple microservices, can pass the ID on for tracking requests'e6c0ea38-f459-4f84-a9b6-873255e95896'
trxModuleTransaction ModuleThe transaction module'User'
trxNameTransaction NameThis will be the name of the decorated function'getUserList'
fileNameFile NameThe name of the file'services/user.service.ts'
userTokenUser TokenThis is the JWT of the user. You are required to manually set the decoded JWT under the 'user' property of the Express request.{ "iss": "issuer", "sub": "subject", "aud": "audience", "jti": "tokenid", "exp": 123, "iat": 456}
timeTakenInMillisTime Taken in MillisecondsThe time the request took from request received to response sent61877
trxStatusTransaction StatusTransaction success is defined by function successful execution, or returning a resolved promise. Transaction failure is defined function throwing or returning a rejected promise.'SUCCESS' / 'FAILURE'
additionalInfo.urlURLThe full URL path'/list?types[]=leave'
additionalInfo.methodMethodThe HTTP method'GET'
additionalInfo.resultResultThe result of the returned function. Only logged if options.toLogResult is set to true. Use options.redactedProperties to add object properties to redact from the logged result{ aPublicValue: 'OK', 'aSecretValue': '[REDACTED]'
additionalInfo.errorErrorThe error thrown by the function, only when status is 'FAILURE''new Error('error')'

Class, Method & Function decorators for Express services (Works out of the box for Express/Koa servers)

Purpose

Glogger decorators give you standardized logging for functions in your application.

For example, one of your routes invokes a function that makes a call to persist an item in your a DB, then returns results from those systems.

You can decorate the function that makes that DB call to get a rich view of that function invocation, including which Express route your user called that invoked this function, the transaction ID, some details of the user that made the request (if available in the request), and results/errors

Works out of the box for decorating functions in an Express / Koa server.


Metadata

All functions being logged must take in an IExpressRequest object as its first parameter, even if the function itself doesn't require it.

You need to use the enhanceReqWithTransactionAndTime above for trxId & timeTakenInMillis to work.

Decorator will log functions with the following metadata:

MetadataFull NameWhat is it?Example
trxIdTransaction IDA randomly generated uuidv4 added to the express request by the enhanceReqWithTransactionAndTime middleware. If using multiple microservices, can pass the ID on for tracking requests'e6c0ea38-f459-4f84-a9b6-873255e95896'
trxModuleTransaction ModuleThe transaction module'User'
trxNameTransaction NameThis will be the name of the decorated function'getUserList'
fileNameFile NameThe name of the file'services/user.service.ts'
userTokenUser TokenThis is the JWT of the user. You are required to manually set the decoded JWT under the 'user' property of the Express request.{ "iss": "issuer", "sub": "subject", "aud": "audience", "jti": "tokenid", "exp": 123, "iat": 456}
timeTakenInMillisTime Taken in MillisecondsThe time the request took from request received to response sent61877
trxStatusTransaction StatusTransaction success is defined by function successful execution, or returning a resolved promise. Transaction failure is defined function throwing or returning a rejected promise.'SUCCESS' / 'FAILURE'
additionalInfo.urlURLThe full URL path'/list?types[]=leave'
additionalInfo.methodMethodThe HTTP method'GET'
additionalInfo.resultResultThe result of the returned function. Only logged if options.toLogResult is set to true. Use options.redactedProperties to add object properties to redact from the logged result{ aPublicValue: 'OK', 'aSecretValue': '[REDACTED]'
additionalInfo.errorErrorThe error thrown by the function, only when status is 'FAILURE''new Error('error')'

Decorators

Glogger decorators allow users to log functions & class method invocations in a standardized way w/o littering logger.info() all over your functions. This makes your code cleaner and easier to read.

This library exports the following decorators.

Decorator FactoryPurpose
LoggedClassDecorate all class methods except constructor
LoggedMethodDecorate a class method
LoggedFunctionDecorate a raw function

All the above are decorator factories. In order to create the decorator, they take in the following parameters:

ParameterExplanationRequired?Example
loggera GLogger instancerequirednew GLogger()
metadatametadata including transaction category, transaction module, & optional filenamerequired
metadata.trxCategoryTransaction categoryrequiredTransactionCategory.TRANS
metadata.trxModuleTransaction modulerequired'User'
optionsOptional option parameteroptional
options.toLogResultwhether to log the return value of the decorated function. Defaults to false.optionaltrue/false
options.toLogSuccessTxnwhether to log the success of the decorated function. Defaults to true.optionaltrue/false
options.redactedPropertiesif options.toLogResult set to true, use this array for properties from the function return value you don't want logged. works for both objects with nested properties and objects inside of arrays. you can also pass in an integer to redact a particular item in an arrayoptional['mySecretProperty', 0]

Examples

See examples folder for usage.

Or you can clone this repo and run:

  • npm i then,
  • npm run example for base logger and decorator demo
  • npm run example-server for middleware demo

Troubleshooting

ScenarioResolution
Getting '' for the transaction IDAll functions being logged must take in the request object IExpressRequest as its first parameter, even if the function itself doesn't require it.

版本与发布记录

@dyihoon90/glogging 共发布 54 个版本,首次发布于 2020/09/24;过去 12 个月发布了 4 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.0.5latest2026/06/025 个月前
4.0.42026/06/025 个月前
4.0.32026/04/216 个月前
4.0.22026/04/146 个月前
4.0.02025/02/211.7 年前
3.0.8-beta.02025/02/211.7 年前

关于 @dyihoon90/glogging 的常见问题

@dyihoon90/glogging 是什么?

HTTP request logging middleware & transaction function decorator for express, using winston

如何安装 @dyihoon90/glogging?

在项目目录运行 npm install @dyihoon90/glogging,或使用 pnpm add / yarn add / bun add。

@dyihoon90/glogging 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dyihoon90/glogging 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@dyihoon90/glogging 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@dyihoon90/glogging 可以商用吗?

@dyihoon90/glogging 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dyihoon90/glogging 的下载量有多少?

根据 npm 官方下载统计,@dyihoon90/glogging 在 2026/10/13 – 2026/11/11 这 30 天内被下载 4,936 次,日均约 165 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dyihoon90/glogging 还在维护吗?

最新版本 4.0.5 发布于 2026/06/02(5 个月前);至今共发布 54 个版本,其中过去 12 个月发布了 4 个;首次发布于 2020/09/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。