Skip to content

feat: #560 disable console log #590

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 11 commits into from
Nov 7, 2023
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
## 4.14.0 [unreleased]

### Features

1. [#590](https://github.com/influxdata/influxdb-client-csharp/pull/590): Allows disable Trace verbose messages

### Dependencies
Update dependencies:

Expand Down
6 changes: 5 additions & 1 deletion Client.Core.Test/AbstractTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ namespace InfluxDB.Client.Core.Test
{
public class AbstractTest
{
private static readonly TraceListener ConsoleOutListener = new TextWriterTraceListener(Console.Out);
private static readonly TraceListener ConsoleOutListener = new TextWriterTraceListener(Console.Out)
{
Filter = InfluxDBTraceFilter.SuppressInfluxVerbose()
};

private static readonly int DefaultWait = 10;
private static readonly int DefaultInfluxDBSleep = 100;

Expand Down
67 changes: 67 additions & 0 deletions Client.Core/InfluxDBTraceFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System.Diagnostics;
using System.Linq;

namespace InfluxDB.Client.Core
{
/// <summary>
/// The <see cref="InfluxDBTraceFilter"/> is used to filter client trace messages by category.
/// </summary>
public class InfluxDBTraceFilter : TraceFilter
{
public const string CategoryInflux = "influx-client";
public const string CategoryInfluxError = "influx-client-error";
public const string CategoryInfluxQuery = "influx-client-query";
public const string CategoryInfluxQueryError = "influx-client-query-error";
public const string CategoryInfluxWrite = "influx-client-write";
public const string CategoryInfluxWriteError = "influx-client-write-error";
public const string CategoryInfluxLogger = "influx-client-logger";

private readonly string[] _categoryToFilter;
private readonly bool _keep;

public InfluxDBTraceFilter(string[] categoryToFilter, bool keep)
{
_categoryToFilter = categoryToFilter;
_keep = keep;
}

public override bool ShouldTrace(TraceEventCache eventCache, string source, TraceEventType eventType, int id,
string formatOrMessage, object[] args, object data, object[] dataArray)
{
return _categoryToFilter.Any(x => x == source) ^ _keep;
}

/// <summary>
/// Suppress all client trace messages.
/// </summary>
/// <returns>Trace Filter</returns>
public static InfluxDBTraceFilter SuppressInflux()
{
return new InfluxDBTraceFilter(new string[]
{
CategoryInflux,
CategoryInfluxError,
CategoryInfluxQuery,
CategoryInfluxQueryError,
CategoryInfluxWrite,
CategoryInfluxWriteError,
CategoryInfluxLogger
}, false);
}

/// <summary>
/// Suppress all client trace messages except <see cref="CategoryInfluxError"/>, <see cref="CategoryInfluxQueryError"/>, <see cref="CategoryInfluxWriteError"/>.
/// </summary>
/// <returns>Trace Filter</returns>
public static InfluxDBTraceFilter SuppressInfluxVerbose()
{
return new InfluxDBTraceFilter(new string[]
{
CategoryInflux,
CategoryInfluxQuery,
CategoryInfluxWrite,
CategoryInfluxLogger
}, false);
}
}
}
5 changes: 3 additions & 2 deletions Client.Core/Internal/AbstractQueryClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -321,8 +321,9 @@ protected void CatchOrPropagateException(Exception exception,
//
if (IsCloseException(exception))
{
Trace.WriteLine("Socket closed by remote server or end of data");
Trace.WriteLine(exception);
Trace.WriteLine("Socket closed by remote server or end of data",
InfluxDBTraceFilter.CategoryInfluxQueryError);
Trace.WriteLine(exception, InfluxDBTraceFilter.CategoryInfluxQueryError);
}
else
{
Expand Down
2 changes: 1 addition & 1 deletion Client.Core/Internal/AbstractRestClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ protected async Task<bool> PingAsync(Task<RestResponse> request)
}
catch (Exception e)
{
Trace.WriteLine($"Error: {e.Message}");
Trace.WriteLine($"Error: {e.Message}", InfluxDBTraceFilter.CategoryInfluxError);
return false;
}
}
Expand Down
3 changes: 2 additions & 1 deletion Client.Core/Internal/EnumConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
}
catch (JsonSerializationException e)
{
Trace.WriteLine($"Error converting enum value. Returning null. {e}");
Trace.WriteLine($"Error converting enum value. Returning null. {e}",
InfluxDBTraceFilter.CategoryInfluxError);

return null;
}
Expand Down
16 changes: 8 additions & 8 deletions Client.Core/Internal/LoggingHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public void BeforeIntercept(RestRequest request)
var isBody = Level == LogLevel.Body;
var isHeader = isBody || Level == LogLevel.Headers;

Trace.WriteLine($"--> {request.Method} {request.Resource}");
Trace.WriteLine($"--> {request.Method} {request.Resource}", InfluxDBTraceFilter.CategoryInfluxLogger);

if (isHeader)
{
Expand Down Expand Up @@ -56,12 +56,12 @@ public void BeforeIntercept(RestRequest request)
stringBody = body.Value.ToString();
}

Trace.WriteLine($"--> Body: {stringBody}");
Trace.WriteLine($"--> Body: {stringBody}", InfluxDBTraceFilter.CategoryInfluxLogger);
}
}

Trace.WriteLine("--> END");
Trace.WriteLine("-->");
Trace.WriteLine("--> END", InfluxDBTraceFilter.CategoryInfluxLogger);
Trace.WriteLine("-->", InfluxDBTraceFilter.CategoryInfluxLogger);
}

public object AfterIntercept(int statusCode, Func<IEnumerable<HeaderParameter>> headers, object body)
Expand All @@ -75,7 +75,7 @@ public object AfterIntercept(int statusCode, Func<IEnumerable<HeaderParameter>>
var isBody = Level == LogLevel.Body;
var isHeader = isBody || Level == LogLevel.Headers;

Trace.WriteLine($"<-- {statusCode}");
Trace.WriteLine($"<-- {statusCode}", InfluxDBTraceFilter.CategoryInfluxLogger);

if (isHeader)
{
Expand All @@ -101,11 +101,11 @@ public object AfterIntercept(int statusCode, Func<IEnumerable<HeaderParameter>>

if (!string.IsNullOrEmpty(stringBody))
{
Trace.WriteLine($"<-- Body: {stringBody}");
Trace.WriteLine($"<-- Body: {stringBody}", InfluxDBTraceFilter.CategoryInfluxLogger);
}
}

Trace.WriteLine("<-- END");
Trace.WriteLine("<-- END", InfluxDBTraceFilter.CategoryInfluxLogger);

return freshBody;
}
Expand All @@ -131,7 +131,7 @@ private void LogHeaders(IEnumerable<HeaderParameter> headers, string direction,
var value = string.Equals(emp.Name, "Authorization", StringComparison.OrdinalIgnoreCase)
? "***"
: emp.Value;
Trace.WriteLine($"{direction} {type}: {emp.Name}={value}");
Trace.WriteLine($"{direction} {type}: {emp.Name}={value}", InfluxDBTraceFilter.CategoryInfluxLogger);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions Client/InfluxDBClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -359,8 +359,8 @@ public void Dispose()
}
catch (Exception e)
{
Trace.WriteLine("The signout exception");
Trace.WriteLine(e);
Trace.WriteLine("The signout exception", InfluxDBTraceFilter.CategoryInfluxError);
Trace.WriteLine(e, InfluxDBTraceFilter.CategoryInfluxError);
}

//
Expand Down
5 changes: 3 additions & 2 deletions Client/Internal/ApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using InfluxDB.Client.Core;
using InfluxDB.Client.Core.Internal;
using RestSharp;
using RestSharp.Authenticators;
Expand Down Expand Up @@ -133,8 +134,8 @@ private void InitToken()
}
catch (IOException e)
{
Trace.WriteLine("Cannot retrieve the Session token!");
Trace.WriteLine(e);
Trace.WriteLine("Cannot retrieve the Session token!", InfluxDBTraceFilter.CategoryInfluxError);
Trace.WriteLine(e, InfluxDBTraceFilter.CategoryInfluxError);
return;
}

Expand Down
3 changes: 2 additions & 1 deletion Client/Internal/MeasurementMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ internal PointData ToPoint<TM>(TM measurement, WritePrecision precision)
}
else
{
Trace.WriteLine($"{value} is not supported as Timestamp");
Trace.WriteLine($"{value} is not supported as Timestamp",
InfluxDBTraceFilter.CategoryInfluxError);
}
}
else
Expand Down
4 changes: 3 additions & 1 deletion Client/Internal/RetryAttempt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using InfluxDB.Client.Core;
using InfluxDB.Client.Core.Exceptions;

namespace InfluxDB.Client.Internal
Expand Down Expand Up @@ -141,7 +142,8 @@ internal long GetRetryInterval()
var retryInterval = (long)(rangeStart + (rangeStop - rangeStart) * _random.NextDouble());

Trace.WriteLine("The InfluxDB does not specify \"Retry-After\". " +
$"Use the default retryInterval: {retryInterval}");
$"Use the default retryInterval: {retryInterval}"
, InfluxDBTraceFilter.CategoryInflux);

return retryInterval;
}
Expand Down
27 changes: 27 additions & 0 deletions Client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,33 @@ namespace Examples
}
```

## Filter trace verbose

You can filter out verbose messages from `InfluxDB.Client` by using TraceListener.

```cs
using System;
using System.Diagnostics;
using InfluxDB.Client.Core;

namespace Examples
{
public static class MyProgram
{
public static void Main()
{
TraceListener ConsoleOutListener = new TextWriterTraceListener(Console.Out)
{
Filter = CategoryTraceFilter.SuppressInfluxVerbose(),
};
Trace.Listeners.Add(ConsoleOutListener);

// My code ...
}
}
}
````

## Management API

The client has following management API:
Expand Down
2 changes: 1 addition & 1 deletion Client/UsersApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ public async Task MeUpdatePasswordAsync(string oldPassword, string newPassword,
var me = await MeAsync(cancellationToken).ConfigureAwait(false);
if (me == null)
{
Trace.WriteLine("User is not authenticated.");
Trace.WriteLine("User is not authenticated.", InfluxDBTraceFilter.CategoryInfluxError);
return;
}

Expand Down
23 changes: 15 additions & 8 deletions Client/WriteApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -300,27 +300,32 @@ protected internal WriteApi(
switch (notification.Kind)
{
case NotificationKind.OnNext:
Trace.WriteLine($"The batch item: {notification} was processed successfully.");
Trace.WriteLine($"The batch item: {notification} was processed successfully."
, InfluxDBTraceFilter.CategoryInfluxWrite);
break;
case NotificationKind.OnError:
Trace.WriteLine(
$"The batch item wasn't processed successfully because: {notification.Exception}");
$"The batch item wasn't processed successfully because: {notification.Exception}"
, InfluxDBTraceFilter.CategoryInfluxWriteError);
break;
default:
Trace.WriteLine($"The batch item: {notification} was processed");
Trace.WriteLine($"The batch item: {notification} was processed"
, InfluxDBTraceFilter.CategoryInfluxWrite);
break;
}
},
exception =>
{
Publish(new WriteRuntimeExceptionEvent(exception));
_disposed = true;
Trace.WriteLine($"The unhandled exception occurs: {exception}");
Trace.WriteLine($"The unhandled exception occurs: {exception}"
, InfluxDBTraceFilter.CategoryInfluxWriteError);
},
() =>
{
_disposed = true;
Trace.WriteLine("The WriteApi was disposed.");
Trace.WriteLine("The WriteApi was disposed."
, InfluxDBTraceFilter.CategoryInfluxWrite);
});
}

Expand All @@ -337,7 +342,7 @@ internal void ReleaseAndClose(int millis = 30000)
{
_unsubscribeDisposeCommand.Dispose(); // avoid duplicate call to dispose

Trace.WriteLine("Flushing batches before shutdown.");
Trace.WriteLine("Flushing batches before shutdown.", InfluxDBTraceFilter.CategoryInfluxWrite);

if (!_subject.IsDisposed)
{
Expand Down Expand Up @@ -572,7 +577,8 @@ internal override string ToLineProtocol()
{
if (!_point.HasFields())
{
Trace.WriteLine($"The point: ${_point} doesn't contains any fields, skipping");
Trace.WriteLine($"The point: ${_point} doesn't contains any fields, skipping",
InfluxDBTraceFilter.CategoryInfluxWrite);

return null;
}
Expand Down Expand Up @@ -603,7 +609,8 @@ internal override string ToLineProtocol()
var point = _converter.ConvertToPointData(_measurement, Options.Precision);
if (!point.HasFields())
{
Trace.WriteLine($"The point: ${point} doesn't contains any fields, skipping");
Trace.WriteLine($"The point: ${point} doesn't contains any fields, skipping",
InfluxDBTraceFilter.CategoryInfluxWrite);

return null;
}
Expand Down
3 changes: 2 additions & 1 deletion Client/WriteApiAsync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,8 @@ private Task WriteData(string org, string bucket, WritePrecision precision, IEnu
var sb = ToLineProtocolBody(data);
if (sb.Length == 0)
{
Trace.WriteLine($"The writes: {data} doesn't contains any Line Protocol, skipping");
Trace.WriteLine($"The writes: {data} doesn't contains any Line Protocol, skipping",
InfluxDBTraceFilter.CategoryInfluxWrite);
return Task.CompletedTask;
}

Expand Down
4 changes: 3 additions & 1 deletion Client/Writes/Events.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Diagnostics;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Core;

namespace InfluxDB.Client.Writes
{
Expand All @@ -18,7 +19,8 @@ public WriteSuccessEvent(string organization, string bucket, WritePrecision prec

internal override void LogEvent()
{
Trace.WriteLine("The data was successfully written to InfluxDB 2.");
Trace.WriteLine("The data was successfully written to InfluxDB 2.",
InfluxDBTraceFilter.CategoryInfluxWrite);
}
}

Expand Down