Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@treelab/logger-metrics-middleware

Package Overview
Dependencies
Maintainers
12
Versions
37
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@treelab/logger-metrics-middleware - npm Package Compare versions

Comparing version 1.0.1-beta to 1.0.1-beta-6

3

dist/http-logger.d.ts
import { HttpMiddlewareConfig } from './interfaces';
export declare function HttpLoggerMiddleware(options?: HttpMiddlewareConfig): (req: any, _res: any, next: any) => any;
export declare function ExpressHttpLoggerMiddleware(options?: HttpMiddlewareConfig): (req: any, _res: any, next: any) => any;
export declare function KoaHttpLoggerMiddleware(options?: HttpMiddlewareConfig): (ctx: any, next: any) => Promise<any>;
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpLoggerMiddleware = void 0;
exports.KoaHttpLoggerMiddleware = exports.ExpressHttpLoggerMiddleware = void 0;
const interfaces_1 = require("./interfaces");

@@ -8,2 +17,3 @@ const jwt_decode_1 = require("jwt-decode");

const metrics_1 = require("./metrics");
const kafka_interface_1 = require("@nestjs/microservices/external/kafka.interface");
const skipPaths = [

@@ -21,20 +31,8 @@ '/',

];
function HttpLoggerMiddleware(options = {}) {
function ExpressHttpLoggerMiddleware(options = {}) {
return (req, _res, next) => {
var _a;
if (skipPaths.includes(req.url) || req.method === 'OPTIONS') {
return next();
}
let log = {
customTag: process.env['AppName'] || 'treelab-svc',
scheme: 'http',
requestId: req.headers['x-request-id'] || '',
transaction: ((_a = req.body) === null || _a === void 0 ? void 0 : _a.operationName) || req.url,
date: new Date(),
method: req.method,
duration: 0,
level: interfaces_1.LogLevel.INFO,
clientip: req.headers['x-forwarded-for'] || ''
};
addOptional(req, log);
let log = addOptional(req);
_res.startTime = process.hrtime();

@@ -90,12 +88,68 @@ _res.locals.requestId = log.requestId;

}
exports.HttpLoggerMiddleware = HttpLoggerMiddleware;
function addOptional(req, log) {
if (req.headers['authorization']) {
exports.ExpressHttpLoggerMiddleware = ExpressHttpLoggerMiddleware;
function KoaHttpLoggerMiddleware(options = {}) {
return (ctx, next) => __awaiter(this, void 0, void 0, function* () {
if (skipPaths.includes(ctx.path) || ctx.method === 'OPTIONS') {
return next();
}
const startTime = Date.now();
let log = {};
let status = 200;
try {
yield next();
log = addOptional(ctx.request, ctx);
log.duration = Date.now() - startTime;
}
catch (err) {
log.level = kafka_interface_1.logLevel.ERROR;
log.err = err;
status = err.status || 500;
const code = err.code || 'SYSTEM_ERROR';
const error = status === 500 && process.env.NODE_ENV.startsWith('prod')
? 'Internal Server Error'
: err.message;
ctx.body = { message: error, code, httpStatus: status };
if (err.details) {
ctx.body.details = err.details;
}
ctx.status = status;
}
finally {
metrics_1.histogram.labels(log.customTag, 'http', log.transaction, status.toString()).observe(log.duration);
if (options.prettyPrint) {
console.log(log);
}
else {
try {
console.log(JSON.stringify(log));
}
catch (_a) { }
}
}
});
}
exports.KoaHttpLoggerMiddleware = KoaHttpLoggerMiddleware;
function addOptional(req, ctx) {
var _a;
let log = {
customTag: process.env['AppName'] || 'treelab-svc',
scheme: 'http',
requestId: req.headers['x-request-id'] || '',
transaction: ((_a = req.body) === null || _a === void 0 ? void 0 : _a.operationName) || req.url || ctx.path,
date: new Date(),
method: req.method || ctx.method,
duration: 0,
level: interfaces_1.LogLevel.INFO,
clientip: req.headers['x-forwarded-for'] || ''
};
req.locals.requestId = log.requestId;
let authorization = req.headers['authorization'] || '';
if (authorization) {
let parsed;
try {
parsed = (0, jwt_decode_1.default)(req.headers['authorization'].split('Bearer ')[1]);
log.token = req.headers['authorization'].split('Bearer ')[1];
parsed = (0, jwt_decode_1.default)(authorization.split('Bearer ')[1]);
log.token = authorization.split('Bearer ')[1];
log.userId = parsed.userId;
}
catch (_a) { }
catch (_b) { }
}

@@ -111,9 +165,10 @@ if (req.body && req.body['variables']) {

}
if (req.body) {
if (_.isEmpty(req.body)) {
log.body = req.body;
}
if (req.query) {
if (_.isEmpty(req.query)) {
log.query = req.query;
}
return log;
}
//# sourceMappingURL=http-logger.js.map

@@ -1,2 +0,2 @@

export { HttpLoggerMiddleware } from './http-logger';
export { ExpressHttpLoggerMiddleware, KoaHttpLoggerMiddleware } from './http-logger';
export { GrpcLoggerMiddleware } from './grpc-logger';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GrpcLoggerMiddleware = exports.HttpLoggerMiddleware = void 0;
exports.GrpcLoggerMiddleware = exports.KoaHttpLoggerMiddleware = exports.ExpressHttpLoggerMiddleware = void 0;
var http_logger_1 = require("./http-logger");
Object.defineProperty(exports, "HttpLoggerMiddleware", { enumerable: true, get: function () { return http_logger_1.HttpLoggerMiddleware; } });
Object.defineProperty(exports, "ExpressHttpLoggerMiddleware", { enumerable: true, get: function () { return http_logger_1.ExpressHttpLoggerMiddleware; } });
Object.defineProperty(exports, "KoaHttpLoggerMiddleware", { enumerable: true, get: function () { return http_logger_1.KoaHttpLoggerMiddleware; } });
var grpc_logger_1 = require("./grpc-logger");
Object.defineProperty(exports, "GrpcLoggerMiddleware", { enumerable: true, get: function () { return grpc_logger_1.GrpcLoggerMiddleware; } });
//# sourceMappingURL=index.js.map

@@ -9,6 +9,6 @@ export interface LogModel {

duration: number;
message?: string;
msg?: string;
method?: string;
query?: string;
body?: string;
query?: any;
body?: any;
clientip?: string;

@@ -19,2 +19,3 @@ tableId?: string;

token?: string;
err?: any;
}

@@ -21,0 +22,0 @@ export interface HttpMiddlewareConfig {

{
"name": "@treelab/logger-metrics-middleware",
"description": "nest js logger-metrics-middleware",
"version": "1.0.1-beta",
"version": "1.0.1-beta-6",
"author": "simon.shi <simon.shi@treelab.co>",

@@ -35,3 +35,2 @@ "homepage": "https://github.com/treelab/treelab-infra-utils/tree/master/treelab-log-metrics",

"@nestjs/common": "^8.4.0",
"@nestjs/core": "^8.4.1",
"@nestjs/microservices": "^8.4.0",

@@ -38,0 +37,0 @@ "@types/node": "^17.0.21",

@@ -1,7 +0,17 @@

### HTTP Log使用
#### HTTP Log使用
### 3.HttpLog中间件配置说明
```
{
prettyPrint?: boolean // 是否以json方式输出, 默认false
... // 后续新增..
}
```
### Express || Nestjs 使用
## 1.导入
```
import { HttpLoggerMiddleware } from '@treelab/logger-metrics-middleware'
import { ExpressHttpLoggerMiddleware } from '@treelab/logger-metrics-middleware'
import * as Prometheus from 'prom-client'

@@ -14,3 +24,3 @@ ```

// 日志
app.use(HttpLoggerMiddleware())
app.use(ExpressHttpLoggerMiddleware())

@@ -26,11 +36,2 @@ // 指标

## 3.HttpLog中间件配置说明
```
{
prettyPrint?: boolean // 是否以json方式输出, 默认false
... // 后续新增..
}
```
## 完整例子

@@ -40,3 +41,3 @@ ```

import { AppModule } from './app.module';
import { HttpLoggerMiddleware } from '@treelab/logger-metrics-middleware'
import { ExpressHttpLoggerMiddleware } from '@treelab/logger-metrics-middleware'
import * as Prometheus from 'prom-client'

@@ -48,3 +49,3 @@ import bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(HttpLoggerMiddleware({ prettyPrint: false}))
app.use(ExpressHttpLoggerMiddleware())

@@ -63,4 +64,28 @@ app.use('/metrics', async (req, res) => {

### Grpc Log 使用
### Koa 使用
## 1.导入
```
import { KoaHttpLoggerMiddleware } from '@treelab/logger-metrics-middleware/dist/http-logger'
import * as Prometheus from 'prom-client'
```
## 2. 使用中间件
```
// 日志
app.use(KoaHttpLoggerMiddleware())
// 指标
router.get('/metrics',async (ctx) => {
ctx.header.set('Content-Type', Prometheus.register.contentType)
const end = await Prometheus.register.metrics()
ctx.body(end)
})
}
```
### Grpc Log 使用(仅支持Nestjs)
## 导入

@@ -77,4 +102,4 @@ ```

@UseInterceptors(GrpcLoggerMiddleware)
@Controller()
@UseInterceptors(GrpcLoggerMiddleware)
@Controller()
export class GrpcController {

@@ -81,0 +106,0 @@ constructor(){}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc