Skip to content

Commit c484124

Browse files
authored
Add logging infrastructure to the Java Client (#2720)
1 parent e78e3db commit c484124

File tree

8 files changed

+124
-10
lines changed

8 files changed

+124
-10
lines changed

clients/java/signalr/src/main/java/Chat.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public static void main(String[] args) throws Exception {
99
Scanner reader = new Scanner(System.in); // Reading from System.in
1010
String input;
1111
input = reader.nextLine();
12-
HubConnection hubConnection = new HubConnection(input);
12+
HubConnection hubConnection = new HubConnection(input, LogLevel.Information);
1313

1414
hubConnection.on("Send", (message) -> {
1515
System.out.println("REGISTERED HANDLER: " + message);
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
public class ConsoleLogger implements Logger {
5+
private LogLevel logLevel;
6+
public ConsoleLogger(LogLevel logLevel) {
7+
this.logLevel = logLevel;
8+
}
9+
10+
@Override
11+
public void log(LogLevel logLevel, String message) {
12+
if(logLevel.value >= this.logLevel.value){
13+
switch (logLevel) {
14+
case Debug:
15+
case Information:
16+
System.out.println(message);
17+
break;
18+
case Warning:
19+
case Error:
20+
case Critical:
21+
System.err.println(message);
22+
break;
23+
}
24+
}
25+
}
26+
27+
@Override
28+
public void log(LogLevel logLevel, String formattedMessage, Object... args) {
29+
if (logLevel.value >= this.logLevel.value) {
30+
formattedMessage = formattedMessage + "%n";
31+
switch (logLevel) {
32+
case Debug:
33+
case Information:
34+
System.out.printf(formattedMessage, args);
35+
break;
36+
case Warning:
37+
case Error:
38+
case Critical:
39+
System.err.printf(formattedMessage, args);
40+
break;
41+
}
42+
}
43+
}
44+
}

clients/java/signalr/src/main/java/HubConnection.java

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,22 @@ public class HubConnection {
1818
private Boolean handshakeReceived = false;
1919
private static final String RECORD_SEPARATOR = "\u001e";
2020
private HubConnectionState connectionState = HubConnectionState.DISCONNECTED;
21+
private Logger logger;
2122

22-
public HubConnection(String url, Transport transport) {
23+
public HubConnection(String url, Transport transport, Logger logger){
2324
this.url = url;
2425
this.protocol = new JsonHubProtocol();
26+
this.logger = logger;
2527
this.callback = (payload) -> {
2628

2729
if (!handshakeReceived) {
2830
int handshakeLength = payload.indexOf(RECORD_SEPARATOR) + 1;
2931
String handshakeResponseString = payload.substring(0, handshakeLength - 1);
3032
HandshakeResponseMessage handshakeResponse = HandshakeProtocol.parseHandshakeResponse(handshakeResponseString);
3133
if (handshakeResponse.error != null) {
32-
throw new Exception("Error in handshake " + handshakeResponse.error);
34+
String errorMessage = "Error in handshake " + handshakeResponse.error;
35+
logger.log(LogLevel.Error, errorMessage);
36+
throw new Exception(errorMessage);
3337
}
3438
handshakeReceived = true;
3539

@@ -43,36 +47,41 @@ public HubConnection(String url, Transport transport) {
4347
HubMessage[] messages = protocol.parseMessages(payload);
4448

4549
for (HubMessage message : messages) {
50+
logger.log(LogLevel.Debug,"Received message of type %s", message.getMessageType());
4651
switch (message.getMessageType()) {
4752
case INVOCATION:
4853
InvocationMessage invocationMessage = (InvocationMessage)message;
49-
if (message != null && handlers.containsKey(invocationMessage.target)) {
54+
if (handlers.containsKey(invocationMessage.target)) {
5055
ArrayList<Object> args = gson.fromJson((JsonArray)invocationMessage.arguments[0], (new ArrayList<>()).getClass());
5156
List<ActionBase> actions = handlers.get(invocationMessage.target);
5257
if (actions != null) {
58+
logger.log(LogLevel.Debug, "Invoking handlers for target %s", invocationMessage.target);
5359
for (ActionBase action: actions) {
5460
action.invoke(args.toArray());
5561
}
5662
}
63+
} else {
64+
logger.log(LogLevel.Warning, "Failed to find handler for %s method", invocationMessage.target);
5765
}
5866
break;
5967
case STREAM_INVOCATION:
6068
case STREAM_ITEM:
6169
case CLOSE:
6270
case CANCEL_INVOCATION:
6371
case COMPLETION:
64-
throw new UnsupportedOperationException("The message type " + message.getMessageType() + " is not supported yet.");
72+
logger.log(LogLevel.Error, "This client does not support %s messages", message.getMessageType());
73+
74+
throw new UnsupportedOperationException(String.format("The message type %s is not supported yet.", message.getMessageType()));
6575
case PING:
6676
// We don't need to do anything in the case of a ping message.
67-
// The other message types aren't supported
6877
break;
6978
}
7079
}
7180
};
7281

7382
if (transport == null){
7483
try {
75-
this.transport = new WebSocketTransport(this.url);
84+
this.transport = new WebSocketTransport(this.url, this.logger);
7685
} catch (URISyntaxException e) {
7786
e.printStackTrace();
7887
}
@@ -81,42 +90,57 @@ public HubConnection(String url, Transport transport) {
8190
}
8291
}
8392

93+
public HubConnection(String url, Transport transport) {
94+
this(url, transport, new NullLogger());
95+
}
96+
8497
public HubConnection(String url) {
85-
this(url, null);
98+
this(url, null, new NullLogger());
99+
}
100+
101+
public HubConnection(String url, LogLevel logLevel){
102+
this(url, null, new ConsoleLogger(logLevel));
86103
}
87104

88105
public HubConnectionState getConnectionState() {
89106
return connectionState;
90107
}
91108

92109
public void start() throws Exception {
110+
logger.log(LogLevel.Debug, "Starting HubConnection");
93111
transport.setOnReceive(this.callback);
94112
transport.start();
95113
String handshake = HandshakeProtocol.createHandshakeRequestMessage(new HandshakeRequestMessage(protocol.getName(), protocol.getVersion()));
96114
transport.send(handshake);
97115
connectionState = HubConnectionState.CONNECTED;
116+
logger.log(LogLevel.Information, "HubConnected started");
98117
}
99118

100119
public void stop(){
120+
logger.log(LogLevel.Debug, "Stopping HubConnection");
101121
transport.stop();
102122
connectionState = HubConnectionState.DISCONNECTED;
123+
logger.log(LogLevel.Information, "HubConnection stopped");
103124
}
104125

105126
public void send(String method, Object... args) throws Exception {
106127
InvocationMessage invocationMessage = new InvocationMessage(method, args);
107128
String message = protocol.writeMessage(invocationMessage);
129+
logger.log(LogLevel.Debug, "Sending message");
108130
transport.send(message);
109131
}
110132

111133
public Subscription on(String target, Action callback) {
112134
ActionBase action = args -> callback.invoke();
113135
handlers.put(target, action);
136+
logger.log(LogLevel.Trace, "Registering handler for client method: %s", target);
114137
return new Subscription(handlers, action, target);
115138
}
116139

117140
public <T1> Subscription on(String target, Action1<T1> callback, Class<T1> param1) {
118141
ActionBase action = params -> callback.invoke(param1.cast(params[0]));
119142
handlers.put(target, action);
143+
logger.log(LogLevel.Trace, "Registering handler for client method: %s", target);
120144
return new Subscription(handlers, action, target);
121145
}
122146

@@ -125,6 +149,7 @@ public <T1, T2> Subscription on(String target, Action2<T1, T2> callback, Class<T
125149
callback.invoke(param1.cast(params[0]), param2.cast(params[1]));
126150
};
127151
handlers.put(target, action);
152+
logger.log(LogLevel.Trace, "Registering handler for client method: %s", target);
128153
return new Subscription(handlers, action, target);
129154
}
130155

@@ -134,6 +159,7 @@ public <T1, T2, T3> Subscription on(String target, Action3<T1, T2, T3> callback,
134159
callback.invoke(param1.cast(params[0]), param2.cast(params[1]), param3.cast(params[2]));
135160
};
136161
handlers.put(target, action);
162+
logger.log(LogLevel.Trace, "Registering handler for client method: %s", target);
137163
return new Subscription(handlers, action, target);
138164
}
139165

@@ -143,6 +169,7 @@ public <T1, T2, T3, T4> Subscription on(String target, Action4<T1, T2, T3, T4> c
143169
callback.invoke(param1.cast(params[0]), param2.cast(params[1]), param3.cast(params[2]), param4.cast(params[3]));
144170
};
145171
handlers.put(target, action);
172+
logger.log(LogLevel.Trace, "Registering handler for client method: %s", target);
146173
return new Subscription(handlers, action, target);
147174
}
148175

@@ -153,6 +180,7 @@ public <T1, T2, T3, T4, T5> Subscription on(String target, Action5<T1, T2, T3, T
153180
param5.cast(params[4]));
154181
};
155182
handlers.put(target, action);
183+
logger.log(LogLevel.Trace, "Registering handler for client method: %s", target);
156184
return new Subscription(handlers, action, target);
157185
}
158186

@@ -163,6 +191,7 @@ public <T1, T2, T3, T4, T5, T6> Subscription on(String target, Action6<T1, T2, T
163191
param5.cast(params[4]) ,param6.cast(params[5]));
164192
};
165193
handlers.put(target, action);
194+
logger.log(LogLevel.Trace, "Registering handler for client method: %s", target);
166195
return new Subscription(handlers, action, target);
167196
}
168197

@@ -173,6 +202,7 @@ public <T1, T2, T3, T4, T5, T6, T7> Subscription on(String target, Action7<T1, T
173202
param5.cast(params[4]) ,param6.cast(params[5]), param7.cast(params[6]));
174203
};
175204
handlers.put(target, action);
205+
logger.log(LogLevel.Trace, "Registering handler for client method: %s", target);
176206
return new Subscription(handlers, action, target);
177207
}
178208

@@ -183,10 +213,12 @@ public <T1, T2, T3, T4, T5, T6, T7, T8> Subscription on(String target, Action8<T
183213
param5.cast(params[4]) ,param6.cast(params[5]), param7.cast(params[6]), param8.cast(params[7]));
184214
};
185215
handlers.put(target, action);
216+
logger.log(LogLevel.Trace, "Registering handler for client method: %s", target);
186217
return new Subscription(handlers, action, target);
187218
}
188219

189220
public void remove(String name) {
190221
handlers.remove(name);
222+
logger.log(LogLevel.Trace, "Removing handlers for client method %s" , name);
191223
}
192224
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
public enum LogLevel {
5+
Trace(0),
6+
Debug(1),
7+
Information(2),
8+
Warning(3),
9+
Error(4),
10+
Critical(5),
11+
None(6);
12+
13+
public int value;
14+
LogLevel(int id) { this.value = id; }
15+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
public interface Logger {
5+
void log(LogLevel logLevel, String message);
6+
void log(LogLevel logLevel, String formattedMessage, Object ... args);
7+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
public class NullLogger implements Logger {
5+
@Override
6+
public void log(LogLevel logLevel, String message) { }
7+
8+
@Override
9+
public void log(LogLevel logLevel, String formattedMessage, Object... args) { }
10+
}

clients/java/signalr/src/main/java/WebSocketTransport.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,16 @@ public class WebSocketTransport implements Transport {
1111
private WebSocketClient webSocketClient;
1212
private OnReceiveCallBack onReceiveCallBack;
1313
private URI url;
14+
private Logger logger;
1415

1516
private static final String HTTP = "http";
1617
private static final String HTTPS = "https";
1718
private static final String WS = "ws";
1819
private static final String WSS = "wss";
1920

20-
public WebSocketTransport(String url) throws URISyntaxException {
21+
public WebSocketTransport(String url, Logger logger) throws URISyntaxException {
2122
this.url = formatUrl(url);
23+
this.logger = logger;
2224
}
2325

2426
public URI getUrl(){
@@ -37,8 +39,10 @@ else if(url.startsWith(HTTP)){
3739

3840
@Override
3941
public void start() throws InterruptedException {
42+
logger.log(LogLevel.Debug, "Starting Websocket connection");
4043
webSocketClient = createWebSocket();
4144
webSocketClient.connectBlocking();
45+
logger.log(LogLevel.Information, "WebSocket transport connected to: %s", webSocketClient.getURI());
4246
}
4347

4448
@Override
@@ -49,6 +53,7 @@ public void send(String message) {
4953
@Override
5054
public void setOnReceive(OnReceiveCallBack callback) {
5155
this.onReceiveCallBack = callback;
56+
logger.log(LogLevel.Debug, "OnReceived callback has been set");
5257
}
5358

5459
@Override
@@ -59,6 +64,7 @@ public void onReceive(String message) throws Exception {
5964
@Override
6065
public void stop() {
6166
webSocketClient.closeConnection(0, "HubConnection Stopped");
67+
logger.log(LogLevel.Information, "WebSocket connection stopped");
6268
}
6369

6470
private WebSocketClient createWebSocket() {

clients/java/signalr/src/test/java/WebSocketTransportTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public static Collection protocols(){
3232

3333
@Test
3434
public void checkWebsocketUrlProtocol() throws URISyntaxException {
35-
WebSocketTransport webSocketTransport = new WebSocketTransport(this.url);
35+
WebSocketTransport webSocketTransport = new WebSocketTransport(this.url, new NullLogger());
3636
assertEquals(this.expectedUrl, webSocketTransport.getUrl().toString());
3737
}
3838
}

0 commit comments

Comments
 (0)