Skip to content

Commit a5ae563

Browse files
Merge pull request #276 from shubham1172/shubham1172/customizable-logging
Use a logging module and make it extensible
2 parents 43c7055 + 19461de commit a5ae563

29 files changed

+397
-126
lines changed

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,10 @@
1313
"test:e2e:http": "TEST_SECRET_1=secret_val_1 TEST_SECRET_2=secret_val_2 dapr run --app-id test-suite --app-protocol http --app-port 50001 --dapr-http-port 50000 --components-path ./test/components -- jest --runInBand --detectOpenHandles --testMatch [ '**/test/e2e/http/(client|server).test.ts' ]",
1414
"test:e2e:http:actors": "TEST_SECRET_1=secret_val_1 TEST_SECRET_2=secret_val_2 dapr run --app-id test-suite --app-protocol http --app-port 50001 --dapr-http-port 50000 --components-path ./test/components -- jest --runInBand --detectOpenHandles --testMatch [ '**/test/e2e/http/actors.test.ts' ]",
1515
"test:unit": "jest --runInBand --detectOpenHandles",
16-
"test:unit:all": "npm run test:unit:main && npm run test:unit:actors && npm run test:unit:utils",
16+
"test:unit:all": "npm run test:unit:main && npm run test:unit:actors && npm run test:unit:logger && npm run test:unit:utils",
1717
"test:unit:main": "NODE_ENV=test npm run test:unit 'test/unit/main/.*\\.test\\.ts'",
1818
"test:unit:actors": "NODE_ENV=test npm run test:unit 'test/unit/actor/.*\\.test\\.ts'",
19+
"test:unit:logger": "NODE_ENV=test npm run test:unit 'test/unit/logger/.*\\.test\\.ts'",
1920
"test:unit:utils": "NODE_ENV=test npm run test:unit 'test/unit/utils/.*\\.test\\.ts'",
2021
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
2122
"build": "./scripts/build.sh",

src/actors/runtime/AbstractActor.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ limitations under the License.
1313

1414
import { Temporal } from "@js-temporal/polyfill";
1515
import DaprClient from "../../implementation/Client/DaprClient";
16+
import { Logger } from "../../logger/Logger";
1617
import ActorId from "../ActorId";
1718
import ActorClient from "../client/ActorClient/ActorClient";
1819
import ActorStateManager from "./ActorStateManager";
@@ -42,6 +43,7 @@ export default abstract class AbstractActor {
4243
private readonly actorClient: ActorClient;
4344
private readonly daprStateProvider: StateProvider;
4445
private readonly actorType: any; // set at constructor level
46+
private readonly logger: Logger;
4547

4648
/**
4749
* Instantiates a new Actor
@@ -52,7 +54,7 @@ export default abstract class AbstractActor {
5254
constructor(daprClient: DaprClient, id: ActorId) {
5355
this.daprClient = daprClient;
5456
this.actorClient = new ActorClient(daprClient.getDaprHost(), daprClient.getDaprPort(), daprClient.getCommunicationProtocol(), daprClient.getOptions());
55-
57+
this.logger = new Logger("Actors", "AbstractActor", daprClient.getOptions().logger)
5658
this.id = id;
5759

5860
this.stateManager = new ActorStateManager(this);
@@ -201,7 +203,7 @@ export default abstract class AbstractActor {
201203
}
202204

203205
async receiveReminder(_data: string): Promise<void> {
204-
console.warn(JSON.stringify({
206+
this.logger.warn(JSON.stringify({
205207
error: "ACTOR_METHOD_NOT_IMPLEMENTED",
206208
errorMsg: `A reminder was created for the actor with id: ${this.id} but the method 'receiveReminder' was not implemented`,
207209
}));

src/actors/runtime/ActorManager.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,6 @@ export default class ActorManager<T extends AbstractActor> {
8787

8888
async getActiveActor(actorId: ActorId): Promise<T> {
8989
if (!this.actors.has(actorId.getId())) {
90-
// console.log(`Doesn't have active actor (${actorId.getId()}), activating it`);
9190
await this.activateActor(actorId);
9291
}
9392

src/implementation/Client/DaprClient.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import HTTPClient from './HTTPClient/HTTPClient';
5252
import CommunicationProtocolEnum from '../../enum/CommunicationProtocol.enum';
5353
import { DaprClientOptions } from '../../types/DaprClientOptions';
5454
import { Settings } from '../../utils/Settings.util';
55+
import { Logger } from '../../logger/Logger';
5556

5657
export default class DaprClient {
5758
readonly daprHost: string;
@@ -71,18 +72,21 @@ export default class DaprClient {
7172
readonly configuration: IClientConfiguration;
7273
readonly actor: IClientActorBuilder;
7374

75+
private readonly logger: Logger;
76+
7477
constructor(
7578
daprHost?: string
7679
, daprPort?: string
7780
, communicationProtocol: CommunicationProtocolEnum = CommunicationProtocolEnum.HTTP
7881
, options: DaprClientOptions = {
79-
isKeepAlive: true
80-
}
82+
isKeepAlive: true,
83+
},
8184
) {
8285
this.daprHost = daprHost ?? Settings.getDefaultHost();
8386
this.daprPort = daprPort ?? Settings.getDefaultPort(communicationProtocol);
8487
this.communicationProtocol = communicationProtocol;
8588
this.options = options;
89+
this.logger = new Logger("DaprClient", "DaprClient", this.options.logger);
8690

8791
// Validation on port
8892
if (!/^[0-9]+$/.test(this.daprPort)) {
@@ -142,9 +146,9 @@ export default class DaprClient {
142146
let isHealthyRetryCount = 0;
143147
const isHealthyMaxRetryCount = 60; // 1s startup delay and we try max for 60s
144148

145-
console.log(`[Dapr-JS][Client] Awaiting Sidecar to be Started`);
149+
this.logger.info(`Awaiting Sidecar to be Started`);
146150
while (!isHealthy) {
147-
console.log(`[Dapr-JS][Client] Waiting till Dapr Sidecar Started (#${isHealthyRetryCount})`);
151+
this.logger.verbose(`Waiting for the Dapr Sidecar to start, retry count: (#${isHealthyRetryCount})`);
148152
await NodeJSUtils.sleep(Settings.getDaprSidecarPollingDelayMs());
149153

150154
// Implement API call manually as we need to enable calling without initialization
@@ -171,7 +175,7 @@ export default class DaprClient {
171175
await this.awaitSidecarStarted();
172176
await this.daprClient.start();
173177
await this.daprClient.setIsInitialized(true);
174-
console.log(`[Dapr-JS][Client] Sidecar Started`);
178+
this.logger.info("Sidecar Started");
175179
}
176180

177181
getDaprClient(): IClient {

src/implementation/Client/GRPCClient/GRPCClient.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import IClient from "../../../interfaces/Client/IClient";
1717
import CommunicationProtocolEnum from "../../../enum/CommunicationProtocol.enum";
1818
import { DaprClientOptions } from "../../../types/DaprClientOptions";
1919
import { Settings } from '../../../utils/Settings.util';
20+
import { Logger } from "../../../logger/Logger";
2021

2122
export default class GRPCClient implements IClient {
2223
private isInitialized: boolean;
@@ -26,21 +27,23 @@ export default class GRPCClient implements IClient {
2627
private readonly clientHost: string;
2728
private readonly clientPort: string;
2829
private readonly options: DaprClientOptions;
30+
private readonly logger: Logger;
2931

3032
constructor(
3133
host = Settings.getDefaultHost()
3234
, port = Settings.getDefaultGrpcPort()
3335
, options: DaprClientOptions = {
3436
isKeepAlive: true
35-
}
37+
},
3638
) {
3739
this.clientHost = host;
3840
this.clientPort = port;
3941
this.clientCredentials = grpc.ChannelCredentials.createInsecure();
4042
this.options = options;
43+
this.logger = new Logger("GRPCClient", "GRPCClient", options.logger);
4144
this.isInitialized = false;
4245

43-
console.log(`[Dapr-JS][gRPC] Opening connection to ${this.clientHost}:${this.clientPort}`);
46+
this.logger.info(`Opening connection to ${this.clientHost}:${this.clientPort}`);
4447
this.client = new DaprClient(`${this.clientHost}:${this.clientPort}`, this.clientCredentials);
4548
}
4649

@@ -78,7 +81,7 @@ export default class GRPCClient implements IClient {
7881
return new Promise((resolve, reject) => {
7982
this.client.waitForReady(deadline, (err?) => {
8083
if (err) {
81-
console.error(err);
84+
this.logger.error(`Error waiting for client to be ready: ${err}`);
8285
return reject();
8386
}
8487

src/implementation/Client/GRPCClient/pubsub.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,17 @@ limitations under the License.
1414
import GRPCClient from './GRPCClient';
1515
import { PublishEventRequest } from "../../../proto/dapr/proto/runtime/v1/dapr_pb";
1616
import IClientPubSub from "../../../interfaces/Client/IClientPubSub";
17+
import { Logger } from '../../../logger/Logger';
1718

1819
// https://docs.dapr.io/reference/api/pubsub_api/
1920
export default class GRPCClientPubSub implements IClientPubSub {
2021
client: GRPCClient;
22+
23+
private readonly logger: Logger;
2124

2225
constructor(client: GRPCClient) {
2326
this.client = client;
27+
this.logger = new Logger("GRPCClient", "PubSub", client.getOptions().logger);
2428
}
2529

2630
// @todo: should return a specific typed Promise<TypePubSubPublishResponse> instead of Promise<any>
@@ -34,7 +38,7 @@ export default class GRPCClientPubSub implements IClientPubSub {
3438
const client = this.client.getClient();
3539
client.publishEvent(msgService, (err, _res) => {
3640
if (err) {
37-
console.error(err);
41+
this.logger.error(`publish failed: ${err}`);
3842
return reject(false);
3943
}
4044

src/implementation/Client/HTTPClient/HTTPClient.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import https from "https";
1919
import { DaprClientOptions } from "../../../types/DaprClientOptions";
2020
import { Settings } from '../../../utils/Settings.util';
2121
import { THTTPExecuteParams } from "../../../types/http/THTTPExecuteParams.type"
22+
import { Logger } from "../../../logger/Logger";
2223

2324
export default class HTTPClient implements IClient {
2425
private isInitialized: boolean;
@@ -28,6 +29,7 @@ export default class HTTPClient implements IClient {
2829
private readonly clientPort: string;
2930
private readonly clientUrl: string;
3031
private readonly options: DaprClientOptions;
32+
private readonly logger: Logger;
3133

3234
private readonly httpAgent;
3335
private readonly httpsAgent;
@@ -37,11 +39,12 @@ export default class HTTPClient implements IClient {
3739
, port = Settings.getDefaultHttpPort()
3840
, options: DaprClientOptions = {
3941
isKeepAlive: true
40-
}
42+
},
4143
) {
4244
this.clientHost = host;
4345
this.clientPort = port;
4446
this.options = options;
47+
this.logger = new Logger("HTTPClient", "HTTPClient", this.options.logger);
4548
this.isInitialized = false;
4649

4750
if (!this.clientHost.startsWith('http://') && !this.clientHost.startsWith('https://')) {
@@ -138,7 +141,7 @@ export default class HTTPClient implements IClient {
138141
params.headers["Content-Type"] = "text/plain";
139142
break;
140143
default:
141-
console.log(`Unknown body type: ${typeof params?.body}, defaulting to "text/plain"`);
144+
this.logger.warn(`Unknown body type: ${typeof params?.body}, defaulting to "text/plain"`);
142145
params.headers["Content-Type"] = "text/plain";
143146
break;
144147
}
@@ -153,7 +156,8 @@ export default class HTTPClient implements IClient {
153156
await this.start();
154157
}
155158

156-
// console.log(`${params.method} - ${urlFull} (${params.body})`);
159+
this.logger.debug(`Fetching ${params.method} ${urlFull} with body: (${params.body})`);
160+
157161
const res = await fetch(urlFull, params);
158162

159163
// Parse body
@@ -184,7 +188,7 @@ export default class HTTPClient implements IClient {
184188
}
185189
// All the others
186190
else {
187-
console.log(txtParsed);
191+
this.logger.debug("Execute response text: %s", txtParsed);
188192
throw new Error(JSON.stringify({
189193
error: "UNKNOWN",
190194
error_msg: `An unknown problem occured and we got the status ${res.status} with response ${JSON.stringify(res)}`

src/implementation/Client/HTTPClient/pubsub.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,16 @@ limitations under the License.
1313

1414
import HTTPClient from './HTTPClient';
1515
import IClientPubSub from '../../../interfaces/Client/IClientPubSub';
16+
import { Logger } from '../../../logger/Logger';
1617

1718
// https://docs.dapr.io/reference/api/pubsub_api/
1819
export default class HTTPClientPubSub implements IClientPubSub {
1920
client: HTTPClient;
21+
private readonly logger: Logger;
2022

2123
constructor(client: HTTPClient) {
2224
this.client = client;
25+
this.logger = new Logger("HTTPClient", "PubSub", client.getOptions().logger);
2326
}
2427

2528
async publish(pubSubName: string, topic: string, data: object = {}): Promise<boolean> {
@@ -31,8 +34,8 @@ export default class HTTPClientPubSub implements IClientPubSub {
3134
},
3235
body: JSON.stringify(data),
3336
});
34-
} catch (e) {
35-
console.error(e);
37+
} catch (e: any) {
38+
this.logger.error(`publish failed: ${e}`);
3639
return false;
3740
}
3841

src/implementation/Server/DaprServer.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import HTTPServerActor from './HTTPServer/actor';
3232
import { DaprClientOptions } from '../../types/DaprClientOptions';
3333
import { DaprClient } from '../..';
3434
import { Settings } from '../../utils/Settings.util';
35+
import { Logger } from '../../logger/Logger';
3536

3637
export default class DaprServer {
3738
// App details
@@ -41,6 +42,8 @@ export default class DaprServer {
4142
private readonly daprHost: string;
4243
private readonly daprPort: string;
4344

45+
private readonly logger: Logger;
46+
4447
readonly daprServer: IServer;
4548
readonly pubsub: IServerPubSub;
4649
readonly binding: IServerBinding;
@@ -62,6 +65,7 @@ export default class DaprServer {
6265
this.serverPort = serverPort ?? Settings.getDefaultAppPort(communicationProtocol);
6366
this.daprHost = daprHost ?? Settings.getDefaultHost();
6467
this.daprPort = daprPort ?? Settings.getDefaultPort(communicationProtocol);
68+
this.logger = new Logger("DaprServer", "DaprServer", clientOptions.logger);
6569

6670
// Create a client to interface with the sidecar from the server side
6771
this.client = new DaprClient(daprHost, daprPort, communicationProtocol, clientOptions);
@@ -113,7 +117,7 @@ export default class DaprServer {
113117
await this.client.start();
114118

115119
// We are initialized
116-
console.log(`[Dapr-JS][Server] Sidecar Started`);
120+
this.logger.info("Sidecar Started");
117121
}
118122

119123
async stop(): Promise<void> {

src/implementation/Server/GRPCServer/GRPCServer.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import GRPCServerImpl from "./GRPCServerImpl";
1616
import { AppCallbackService } from "../../../proto/dapr/proto/runtime/v1/appcallback_grpc_pb";
1717
import IServer from "../../../interfaces/Server/IServer";
1818
import { DaprClient } from "../../..";
19+
import { Logger } from "../../../logger/Logger";
1920

2021
// eslint-disable-next-line
2122
export interface IServerType extends grpc.Server { }
@@ -30,21 +31,23 @@ export default class GRPCServer implements IServer {
3031
serverImpl: IServerImplType;
3132
serverCredentials: grpc.ServerCredentials;
3233
client: DaprClient;
34+
private readonly logger: Logger;
3335

3436
constructor(client: DaprClient) {
3537
this.isInitialized = false;
3638

3739
this.serverHost = "";
3840
this.serverPort = "";
3941
this.client = client;
42+
this.logger = new Logger("GRPCServer", "GRPCServer", client.options.logger);
4043

4144
// Create Server
4245
this.server = new grpc.Server();
4346
this.serverCredentials = grpc.ServerCredentials.createInsecure();
44-
this.serverImpl = new GRPCServerImpl();
47+
this.serverImpl = new GRPCServerImpl(client.options.logger);
4548

4649
// Add our implementation
47-
console.log("[Dapr-JS][gRPC] Adding Service Implementation - AppCallbackService")
50+
this.logger.info("Adding Service Implementation - AppCallbackService")
4851
// @ts-ignore
4952
this.server.addService(AppCallbackService, this.serverImpl);
5053
}
@@ -102,14 +105,14 @@ export default class GRPCServer implements IServer {
102105
}
103106

104107
private async initializeBind(): Promise<void> {
105-
console.log(`[Dapr-JS][gRPC] Starting to listen on ${this.serverHost}:${this.serverPort}`);
108+
this.logger.info(`Starting to listen on ${this.serverHost}:${this.serverPort}`);
106109
return new Promise((resolve, reject) => {
107110
this.server.bindAsync(`${this.serverHost}:${this.serverPort}`, this.serverCredentials, (err, _port) => {
108111
if (err) {
109112
return reject(err);
110113
}
111114

112-
console.log(`[Dapr-JS][gRPC] Listening on ${this.serverHost}:${this.serverPort}`);
115+
this.logger.info(`Listening on ${this.serverHost}:${this.serverPort}`);
113116
return resolve();
114117
});
115118
})

0 commit comments

Comments
 (0)