Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 098c425

Browse files
committed
Add ClientId and include LogPrefix in logging to improve tracking clients
1 parent 0d11f3c commit 098c425

2 files changed

Lines changed: 57 additions & 20 deletions

File tree

src/ServiceStack.Redis/RedisNativeClient.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,7 @@ private void Init(RedisEndpoint config)
179179
Ssl = config.Ssl;
180180
IdleTimeOutSecs = config.IdleTimeOutSecs;
181181
ServerVersionNumber = RedisConfig.AssumeServerVersion.GetValueOrDefault();
182+
LogPrefix = "#" + ClientId + " ";
182183
JsConfig.InitStatics();
183184
}
184185

src/ServiceStack.Redis/RedisNativeClient_Utils.cs

Lines changed: 56 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,14 @@ public partial class RedisNativeClient
3939
private const int Unknown = -1;
4040
public static int ServerVersionNumber { get; set; }
4141

42+
private static long IdCounter = 0;
43+
public long ClientId { get; } = Interlocked.Increment(ref IdCounter);
44+
45+
private string LogPrefix = string.Empty;
46+
private void logDebug(object message) => log.Debug(LogPrefix + message);
47+
private void logError(object message) => log.Error(LogPrefix + message);
48+
private void logError(object message, Exception ex) => log.Error(LogPrefix + message, ex);
49+
4250
public int AssertServerVersionNumber()
4351
{
4452
if (ServerVersionNumber == 0)
@@ -98,12 +106,18 @@ private void Connect()
98106

99107
if (!socket.Connected)
100108
{
109+
if (log.IsDebugEnabled)
110+
logDebug("Socket Connect failed");
111+
101112
socket.Close();
102113
socket = null;
103114
DeactivatedAt = DateTime.UtcNow;
104115
return;
105116
}
106117

118+
if (log.IsDebugEnabled)
119+
logDebug("Socket Connected");
120+
107121
Stream networkStream = new NetworkStream(socket);
108122

109123
if (Ssl)
@@ -203,7 +217,7 @@ private void Connect()
203217
}
204218
catch (SocketException)
205219
{
206-
log.Error(ErrorConnect.Fmt(Host, Port));
220+
logError(ErrorConnect.Fmt(Host, Port));
207221
throw;
208222
}
209223
}
@@ -251,7 +265,7 @@ internal bool AssertConnectedSocket()
251265
}
252266
catch (SocketException ex)
253267
{
254-
log.Error(ErrorConnect.Fmt(Host, Port));
268+
logError(ErrorConnect.Fmt(Host, Port));
255269

256270
socket?.Close();
257271

@@ -260,7 +274,7 @@ internal bool AssertConnectedSocket()
260274
DeactivatedAt = DateTime.UtcNow;
261275
var message = Host + ":" + Port;
262276
var throwEx = new RedisException(message, ex);
263-
log.Error(throwEx.Message, ex);
277+
logError(throwEx.Message, ex);
264278
throw throwEx;
265279
}
266280
}
@@ -313,7 +327,7 @@ private RedisResponseException CreateResponseError(string error)
313327
}
314328

315329
var throwEx = new RedisResponseException(error);
316-
log.Error(error);
330+
logError(error);
317331
return throwEx;
318332
}
319333

@@ -329,7 +343,7 @@ private RedisRetryableException CreateRetryableResponseError(string error)
329343

330344
var throwEx = new RedisRetryableException(
331345
$"[{DateTime.UtcNow:HH:mm:ss.fff}] {error}, sPort: {clientPort}, LastCommand: {safeLastCommand}");
332-
log.Error(throwEx.Message);
346+
logError(throwEx.Message);
333347
throw throwEx;
334348
}
335349

@@ -339,7 +353,7 @@ private RedisException CreateConnectionError(Exception originalEx)
339353
var throwEx = new RedisException(
340354
$"[{DateTime.UtcNow:HH:mm:ss.fff}] Unable to Connect: sPort: {clientPort}{(originalEx != null ? ", Error: " + originalEx.Message + "\n" + originalEx.StackTrace : "")}",
341355
originalEx ?? lastSocketException);
342-
log.Error(throwEx.Message);
356+
logError(throwEx.Message);
343357
throw throwEx;
344358
}
345359

@@ -393,6 +407,9 @@ protected void SendUnmanagedExpectSuccess(params byte[][] cmdWithBinaryArgs)
393407
{
394408
bytes = bytes.Combine(GetCmdBytes('$', safeBinaryValue.Length), safeBinaryValue, endData);
395409
}
410+
411+
if (log.IsDebugEnabled && RedisConfig.EnableVerboseLogging)
412+
logDebug(Encoding.UTF8.GetString(bytes, 0, Math.Min(bytes.Length, 50)).Replace("\r\n"," ").SafeSubstring(0,50));
396413

397414
Bstream.Write(bytes, 0, bytes.Length);
398415

@@ -472,6 +489,19 @@ internal void FlushSendBuffer()
472489

473490
if (!Env.IsMono && sslStream == null)
474491
{
492+
if (log.IsDebugEnabled && RedisConfig.EnableVerboseLogging)
493+
{
494+
var sb = StringBuilderCache.Allocate();
495+
foreach (var cmd in cmdBuffer)
496+
{
497+
if (sb.Length > 50)
498+
break;
499+
500+
sb.Append(Encoding.UTF8.GetString(cmd.Array, cmd.Offset, cmd.Count));
501+
}
502+
logDebug("socket.Send: " + StringBuilderCache.ReturnAndFree(sb.Replace("\r\n", " ")).SafeSubstring(0,50));
503+
}
504+
475505
socket.Send(cmdBuffer); //Optimized for Windows
476506
}
477507
else
@@ -507,11 +537,14 @@ public void ResetSendBuffer()
507537
}
508538
}
509539

510-
private int SafeReadByte()
540+
private int SafeReadByte(string name)
511541
{
542+
if (log.IsDebugEnabled && RedisConfig.EnableVerboseLogging)
543+
logDebug(name + "()");
544+
512545
return Bstream.ReadByte();
513546
}
514-
547+
515548
internal TrackThread? TrackThread;
516549

517550
protected T SendReceive<T>(byte[][] cmdWithBinaryArgs,
@@ -575,6 +608,9 @@ protected T SendReceive<T>(byte[][] cmdWithBinaryArgs,
575608
}
576609
catch (Exception outerEx)
577610
{
611+
if (log.IsDebugEnabled)
612+
logDebug("SendReceive Exception: " + outerEx.Message);
613+
578614
var retryableEx = outerEx as RedisRetryableException;
579615
if (retryableEx == null && outerEx is RedisException
580616
|| outerEx is LicenseException)
@@ -610,7 +646,7 @@ private RedisException CreateRetryTimeoutException(TimeSpan retryTimeout, Except
610646
{
611647
DeactivatedAt = DateTime.UtcNow;
612648
var message = "Exceeded timeout of {0}".Fmt(retryTimeout);
613-
log.Error(message);
649+
logError(message);
614650
return new RedisException(message, originalEx);
615651
}
616652

@@ -623,7 +659,7 @@ private Exception GetRetryableException(Exception outerEx)
623659
if (socketEx == null)
624660
return null;
625661

626-
log.Error("SocketException in SendReceive, retrying...", socketEx);
662+
logError("SocketException in SendReceive, retrying...", socketEx);
627663
lastSocketException = socketEx;
628664

629665
socket?.Close();
@@ -742,7 +778,7 @@ protected void Log(string fmt, params object[] args)
742778
if (RedisConfig.EnableVerboseLogging)
743779
return;
744780

745-
log.DebugFormat("{0}", string.Format(fmt, args).Trim());
781+
log.DebugFormat(LogPrefix + "{0}", string.Format(fmt, args).Trim());
746782
}
747783

748784
protected void CmdLog(byte[][] args)
@@ -767,7 +803,7 @@ protected void CmdLog(byte[][] args)
767803
this.lastCommand = this.lastCommand.Substring(0, 100) + "...";
768804
}
769805

770-
log.Debug("S: " + this.lastCommand);
806+
logDebug("S: " + this.lastCommand);
771807
}
772808

773809
//Turn Action into Func Hack
@@ -779,7 +815,7 @@ protected long ExpectSuccessFn()
779815

780816
protected void ExpectSuccess()
781817
{
782-
int c = SafeReadByte();
818+
int c = SafeReadByte(nameof(ExpectSuccess));
783819
if (c == -1)
784820
throw CreateNoMoreDataError();
785821

@@ -794,7 +830,7 @@ protected void ExpectSuccess()
794830

795831
private void ExpectWord(string word)
796832
{
797-
int c = SafeReadByte();
833+
int c = SafeReadByte(nameof(ExpectWord));
798834
if (c == -1)
799835
throw CreateNoMoreDataError();
800836

@@ -812,7 +848,7 @@ private void ExpectWord(string word)
812848

813849
private string ExpectCode()
814850
{
815-
int c = SafeReadByte();
851+
int c = SafeReadByte(nameof(ExpectCode));
816852
if (c == -1)
817853
throw CreateNoMoreDataError();
818854

@@ -839,7 +875,7 @@ internal void ExpectQueued()
839875

840876
public long ReadLong()
841877
{
842-
int c = SafeReadByte();
878+
int c = SafeReadByte(nameof(ReadLong));
843879
if (c == -1)
844880
throw CreateNoMoreDataError();
845881

@@ -928,7 +964,7 @@ private byte[] ParseSingleLine(string r)
928964

929965
private byte[][] ReadMultiData()
930966
{
931-
int c = SafeReadByte();
967+
int c = SafeReadByte(nameof(ReadMultiData));
932968
if (c == -1)
933969
throw CreateNoMoreDataError();
934970

@@ -977,7 +1013,7 @@ private object[] ReadDeeplyNestedMultiData()
9771013

9781014
private object ReadDeeplyNestedMultiDataItem()
9791015
{
980-
int c = SafeReadByte();
1016+
int c = SafeReadByte(nameof(ReadDeeplyNestedMultiDataItem));
9811017
if (c == -1)
9821018
throw CreateNoMoreDataError();
9831019

@@ -1015,7 +1051,7 @@ private object ReadDeeplyNestedMultiDataItem()
10151051

10161052
internal RedisData ReadComplexResponse()
10171053
{
1018-
int c = SafeReadByte();
1054+
int c = SafeReadByte(nameof(ReadComplexResponse));
10191055
if (c == -1)
10201056
throw CreateNoMoreDataError();
10211057

@@ -1056,7 +1092,7 @@ internal RedisData ReadComplexResponse()
10561092

10571093
internal int ReadMultiDataResultCount()
10581094
{
1059-
int c = SafeReadByte();
1095+
int c = SafeReadByte(nameof(ReadMultiDataResultCount));
10601096
if (c == -1)
10611097
throw CreateNoMoreDataError();
10621098

0 commit comments

Comments
 (0)