Skip to content

Commit

Permalink
refactor: refactor implementation of cleanLog
Browse files Browse the repository at this point in the history
implement cleanLog in logger inside
  • Loading branch information
Zack921 committed Jun 1, 2021
1 parent df5d5e6 commit 8e4d573
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 61 deletions.
12 changes: 12 additions & 0 deletions lib/core/logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ type LogLevelStrings = keyof typeof LOG_LEVEL;
type WinstonLogLevel = keyof typeof winstonConfig.syslog.levels;

export class Logger {
private isCleanLog = false;

public logLevel: number

public winstonLogger: WinstonLogger
Expand All @@ -45,7 +47,16 @@ export class Logger {
return this.logLevel;
}

public setCleanLog(isCleanLog: boolean): void {
this.isCleanLog = isCleanLog;
}

public getCleanLog(): boolean {
return this.isCleanLog;
}

public debug(str: string): void {
if (this.isCleanLog) return;
if (!currentContext()) {
console.debug(Logger.formatStr(str, "DEBUG", {
levelLimit: this.logLevel
Expand All @@ -56,6 +67,7 @@ export class Logger {
}

public info(str: string): void {
if (this.isCleanLog) return;
if (!currentContext()) {
console.info(Logger.formatStr(str, "INFO", {
levelLimit: this.logLevel
Expand Down
94 changes: 38 additions & 56 deletions lib/core/runtime/capture/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import currentContext, { RequestLog, Context } from "../../context";
import logger from "../../logger/index";

type requestProtocol = "http:" | "https:";
let isCleanLog = false;

/**
* Convert a URL instance to a http.request options
Expand Down Expand Up @@ -85,10 +84,8 @@ export const hack = <T extends typeof http.request>(
method, hostname, path, port
} = options;

if (!isCleanLog) {
logger.debug(`${logPre} Request begin. ${
method} ${hostname}${port ? `:${port}` : ""} ~ ${path}`);
}
logger.debug(`${logPre} Request begin. ${
method} ${hostname}${port ? `:${port}` : ""} ~ ${path}`);

const requestLog: Partial<RequestLog> = {
SN: context.captureSN,
Expand All @@ -115,11 +112,9 @@ export const hack = <T extends typeof http.request>(
const finishRequest = (): void => {
context.captureRequests.push(requestLog as RequestLog);

if (!isCleanLog) {
logger.debug(`${logPre} Record request info. Response body length: ${
requestLog.responseLength
}`);
}
logger.debug(`${logPre} Record request info. Response body length: ${
requestLog.responseLength
}`);
};

request.once("socket", (socket: Socket): void => {
Expand All @@ -136,13 +131,11 @@ export const hack = <T extends typeof http.request>(
timestamps.dnsTime = timestamps.onLookUp.getTime()
- timestamps.onSocket.getTime();

if (!isCleanLog) {
logger.debug(`${logPre} Dns lookup ${host} -> ${
address || "null"}. Cost ${timestamps.dnsTime}ms`);
}
logger.debug(`${logPre} Dns lookup ${host} -> ${
address || "null"}. Cost ${timestamps.dnsTime}ms`);

if (err) {
if (isCleanLog) {
if (logger.getCleanLog()) {
logger.error(`${logPre} Request: ${JSON.stringify(requestLog)}`);
}

Expand All @@ -155,28 +148,24 @@ export const hack = <T extends typeof http.request>(
socket.once("connect", (): void => {
timestamps.socketConnect = new Date();

if (!isCleanLog) {
logger.debug(`${logPre} Socket connected. Remote: ${
socket.remoteAddress
}:${socket.remotePort}. Cost ${
timestamps.socketConnect.getTime() - timestamps.onSocket.getTime()
} ms`);
}
logger.debug(`${logPre} Socket connected. Remote: ${
socket.remoteAddress
}:${socket.remotePort}. Cost ${
timestamps.socketConnect.getTime() - timestamps.onSocket.getTime()
} ms`);
});

if (socket.remoteAddress) {
timestamps.dnsTime = 0;

if (!isCleanLog) {
logger.debug(`${logPre} Socket reused. Remote: ${
socket.remoteAddress
}:${socket.remotePort}`);
}
logger.debug(`${logPre} Socket reused. Remote: ${
socket.remoteAddress
}:${socket.remotePort}`);
}
});

request.once("error", (error: Error) => {
if (isCleanLog) {
if (logger.getCleanLog()) {
logger.error(`${logPre} Request: ${JSON.stringify(requestLog)}`);
}

Expand All @@ -203,13 +192,11 @@ export const hack = <T extends typeof http.request>(

requestLog.requestHeader = (request as any)._header;
requestLog.requestBody = requestBody;
if (!isCleanLog) {
logger.debug(`${logPre} Request send finish. Body size ${
length
}. Cost: ${
timestamps.requestFinish.getTime() - timestamps.onSocket.getTime()
} ms`);
}
logger.debug(`${logPre} Request send finish. Body size ${
length
}. Cost: ${
timestamps.requestFinish.getTime() - timestamps.onSocket.getTime()
} ms`);

clearDomain();
});
Expand All @@ -225,18 +212,16 @@ export const hack = <T extends typeof http.request>(
requestLog.clientIp = socket.localAddress;
requestLog.clientPort = socket.localPort;

if (!isCleanLog) {
logger.debug(`${logPre} Request on response. Socket chain: ${
socket.localAddress
}:${socket.localPort} > ${
socket.remoteAddress
}:${socket.remotePort}. Response status code: ${
response.statusCode
}. Cost: ${
timestamps.onResponse.getTime()
- timestamps.onSocket.getTime()
} ms`);
}
logger.debug(`${logPre} Request on response. Socket chain: ${
socket.localAddress
}:${socket.localPort} > ${
socket.remoteAddress
}:${socket.remotePort}. Response status code: ${
response.statusCode
}. Cost: ${
timestamps.onResponse.getTime()
- timestamps.onSocket.getTime()
} ms`);

// responseInfo can't retrieve data until response "end" event
const responseInfo = captureIncoming(response);
Expand Down Expand Up @@ -272,14 +257,12 @@ export const hack = <T extends typeof http.request>(

requestLog.responseBody = responseInfo.body.toString("base64");

if (!isCleanLog) {
logger.debug(`${logPre} Response on end. Body size:${
requestLog.responseLength
}. Cost: ${
timestamps.responseClose.getTime()
- timestamps.onSocket.getTime()
} ms`);
}
logger.debug(`${logPre} Response on end. Body size:${
requestLog.responseLength
}. Cost: ${
timestamps.responseClose.getTime()
- timestamps.onSocket.getTime()
} ms`);

finishRequest();
});
Expand All @@ -292,7 +275,6 @@ let hacked = false;
let originHttpRequest = null;
let originHttpsRequest = null;
export const requestHack = (): void => {
isCleanLog = (global.tswConfig && global.tswConfig.cleanLog) || false;
if (!hacked) {
originHttpRequest = http.request;
originHttpsRequest = https.request;
Expand Down
8 changes: 3 additions & 5 deletions lib/core/runtime/dns.hack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ let dnsHacked = false;
let originDnsLookUp = null;

export const dnsHack = (): void => {
const isCleanLog = (global.tswConfig && global.tswConfig.cleanLog) || false;
// Ensure hack can only be run once.
if (!dnsHacked) {
dnsHacked = true;
Expand All @@ -53,14 +52,14 @@ export const dnsHack = (): void => {
? optionsOrCallback
: callbackOrUndefined;

if (!isCleanLog) logger.debug(`dns lookup for ${hostname}`);
logger.debug(`dns lookup for ${hostname}`);

// For http.request, if host is a ip
// It will not entry dns.lookup by default
// https://github.com/nodejs/node/blob/master/lib/net.js#L1002
// But still need this, in case use call dns.lookup directly
if (net.isIP(hostname)) {
if (!isCleanLog) logger.debug(`dns lookup: ${hostname} is a ip`);
logger.debug(`dns lookup: ${hostname} is a ip`);
if (options) {
return lookup.apply(this, [hostname, options, callback]);
}
Expand All @@ -85,8 +84,7 @@ export const dnsHack = (): void => {

const cost = Date.now() - start;
if (!err) {
// eslint-disable-next-line max-len
if (!isCleanLog) logger.debug(`dns lookup [${cost}ms]: ${hostname} > ${address}`);
logger.debug(`dns lookup [${cost}ms]: ${hostname} > ${address}`);
eventBus.emit(EVENT_LIST.DNS_LOOKUP_SUCCESS, address);
} else {
logger.error(`dns lookup [${cost}ms]: ${hostname} > ${address},
Expand Down
4 changes: 4 additions & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { dnsHack, dnsRestore } from "./core/runtime/dns.hack";
import { requestHack, requestRestore } from "./core/runtime/capture/index";
import { winstonHack, winstonRestore } from "./core/winston";
import { eventBus } from "./core/bus";
import logger from "./core/logger";

export const installHacks = (): void => {
httpCreateServerHack();
Expand All @@ -32,6 +33,9 @@ export default async (
): Promise<void> => {
const configAbsolutePath = path.resolve(basePath, configPath);
global.tswConfig = await import(configAbsolutePath);

logger.setCleanLog(global.tswConfig && global.tswConfig.cleanLog);

// eslint-disable-next-line no-restricted-syntax
for (const plugin of global.tswConfig.plugins) {
try {
Expand Down

0 comments on commit 8e4d573

Please sign in to comment.