introduce gRPC logger

pull/2648/head
Jan Tattermusch 9 years ago
parent 01cd209078
commit 0526161385
  1. 7
      src/csharp/Grpc.Core/Grpc.Core.csproj
  2. 33
      src/csharp/Grpc.Core/GrpcEnvironment.cs
  3. 5
      src/csharp/Grpc.Core/Internal/AsyncCall.cs
  4. 13
      src/csharp/Grpc.Core/Internal/AsyncCallBase.cs
  5. 5
      src/csharp/Grpc.Core/Internal/CompletionRegistry.cs
  6. 10
      src/csharp/Grpc.Core/Internal/GrpcThreadPool.cs
  7. 37
      src/csharp/Grpc.Core/Internal/NativeLogRedirector.cs
  8. 17
      src/csharp/Grpc.Core/Internal/ServerCallHandler.cs
  9. 103
      src/csharp/Grpc.Core/Logging/ConsoleLogger.cs
  10. 57
      src/csharp/Grpc.Core/Logging/ILogger.cs
  11. 5
      src/csharp/Grpc.Core/Server.cs
  12. 10
      src/csharp/Grpc.Core/Utils/BenchmarkUtil.cs
  13. 3
      src/csharp/Grpc.IntegrationTesting/SslCredentialsTest.cs

@ -47,7 +47,6 @@
<Compile Include="IServerStreamWriter.cs" /> <Compile Include="IServerStreamWriter.cs" />
<Compile Include="IAsyncStreamWriter.cs" /> <Compile Include="IAsyncStreamWriter.cs" />
<Compile Include="IAsyncStreamReader.cs" /> <Compile Include="IAsyncStreamReader.cs" />
<Compile Include="Internal\GrpcLog.cs" />
<Compile Include="Version.cs" /> <Compile Include="Version.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RpcException.cs" /> <Compile Include="RpcException.cs" />
@ -105,6 +104,9 @@
<Compile Include="VersionInfo.cs" /> <Compile Include="VersionInfo.cs" />
<Compile Include="Internal\CStringSafeHandle.cs" /> <Compile Include="Internal\CStringSafeHandle.cs" />
<Compile Include="KeyCertificatePair.cs" /> <Compile Include="KeyCertificatePair.cs" />
<Compile Include="Logging\ILogger.cs" />
<Compile Include="Logging\ConsoleLogger.cs" />
<Compile Include="Internal\NativeLogRedirector.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="Grpc.Core.nuspec" /> <None Include="Grpc.Core.nuspec" />
@ -135,4 +137,7 @@
</Target> </Target>
<Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.2\build\portable-net45\grpc.dependencies.openssl.redist.targets" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.2\build\portable-net45\grpc.dependencies.openssl.redist.targets')" /> <Import Project="..\packages\grpc.dependencies.openssl.redist.1.0.2.2\build\portable-net45\grpc.dependencies.openssl.redist.targets" Condition="Exists('..\packages\grpc.dependencies.openssl.redist.1.0.2.2\build\portable-net45\grpc.dependencies.openssl.redist.targets')" />
<Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" /> <Import Project="..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets" Condition="Exists('..\packages\grpc.dependencies.zlib.redist.1.2.8.9\build\portable-net45\grpc.dependencies.zlib.redist.targets')" />
<ItemGroup>
<Folder Include="Logging\" />
</ItemGroup>
</Project> </Project>

@ -35,6 +35,7 @@ using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading.Tasks; using System.Threading.Tasks;
using Grpc.Core.Internal; using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils; using Grpc.Core.Utils;
namespace Grpc.Core namespace Grpc.Core
@ -55,6 +56,8 @@ namespace Grpc.Core
static object staticLock = new object(); static object staticLock = new object();
static GrpcEnvironment instance; static GrpcEnvironment instance;
static ILogger logger = new ConsoleLogger();
readonly GrpcThreadPool threadPool; readonly GrpcThreadPool threadPool;
readonly CompletionRegistry completionRegistry; readonly CompletionRegistry completionRegistry;
readonly DebugStats debugStats = new DebugStats(); readonly DebugStats debugStats = new DebugStats();
@ -92,18 +95,39 @@ namespace Grpc.Core
} }
} }
/// <summary>
/// Gets application-wide logger used by gRPC.
/// </summary>
/// <value>The logger.</value>
public static ILogger Logger
{
get
{
return logger;
}
}
/// <summary>
/// Sets the application-wide logger that should be used by gRPC.
/// </summary>
public static void SetLogger(ILogger customLogger)
{
Preconditions.CheckNotNull(customLogger);
logger = customLogger;
}
/// <summary> /// <summary>
/// Creates gRPC environment. /// Creates gRPC environment.
/// </summary> /// </summary>
private GrpcEnvironment() private GrpcEnvironment()
{ {
GrpcLog.RedirectNativeLogs(Console.Error); NativeLogRedirector.Redirect();
grpcsharp_init(); grpcsharp_init();
completionRegistry = new CompletionRegistry(this); completionRegistry = new CompletionRegistry(this);
threadPool = new GrpcThreadPool(this, THREAD_POOL_SIZE); threadPool = new GrpcThreadPool(this, THREAD_POOL_SIZE);
threadPool.Start(); threadPool.Start();
// TODO: use proper logging here // TODO: use proper logging here
Console.WriteLine("GRPC initialized."); Logger.Info("gRPC initialized.");
} }
/// <summary> /// <summary>
@ -154,8 +178,7 @@ namespace Grpc.Core
debugStats.CheckOK(); debugStats.CheckOK();
// TODO: use proper logging here Logger.Info("gRPC shutdown.");
Console.WriteLine("GRPC shutdown.");
} }
/// <summary> /// <summary>
@ -171,7 +194,7 @@ namespace Grpc.Core
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Error occured while shutting down GrpcEnvironment: " + e); Logger.Error(e, "Error occured while shutting down GrpcEnvironment.");
} }
}); });
} }

@ -38,6 +38,7 @@ using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Grpc.Core.Internal; using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils; using Grpc.Core.Utils;
namespace Grpc.Core.Internal namespace Grpc.Core.Internal
@ -47,6 +48,8 @@ namespace Grpc.Core.Internal
/// </summary> /// </summary>
internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse> internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse>
{ {
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>();
Channel channel; Channel channel;
// Completion of a pending unary response if not null. // Completion of a pending unary response if not null.
@ -106,7 +109,7 @@ namespace Grpc.Core.Internal
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Exception occured while invoking completion delegate: " + e); Logger.Error(e, "Exception occured while invoking completion delegate.");
} }
} }
} }

@ -38,6 +38,7 @@ using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Grpc.Core.Internal; using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils; using Grpc.Core.Utils;
namespace Grpc.Core.Internal namespace Grpc.Core.Internal
@ -48,6 +49,8 @@ namespace Grpc.Core.Internal
/// </summary> /// </summary>
internal abstract class AsyncCallBase<TWrite, TRead> internal abstract class AsyncCallBase<TWrite, TRead>
{ {
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>();
readonly Func<TWrite, byte[]> serializer; readonly Func<TWrite, byte[]> serializer;
readonly Func<byte[], TRead> deserializer; readonly Func<byte[], TRead> deserializer;
@ -233,9 +236,9 @@ namespace Grpc.Core.Internal
payload = serializer(msg); payload = serializer(msg);
return true; return true;
} }
catch (Exception) catch (Exception e)
{ {
Console.WriteLine("Exception occured while trying to serialize message"); Logger.Error(e, "Exception occured while trying to serialize message");
payload = null; payload = null;
return false; return false;
} }
@ -248,9 +251,9 @@ namespace Grpc.Core.Internal
msg = deserializer(payload); msg = deserializer(payload);
return true; return true;
} }
catch (Exception) catch (Exception e)
{ {
Console.WriteLine("Exception occured while trying to deserialize message"); Logger.Error(e, "Exception occured while trying to deserialize message.");
msg = default(TRead); msg = default(TRead);
return false; return false;
} }
@ -264,7 +267,7 @@ namespace Grpc.Core.Internal
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Exception occured while invoking completion delegate: " + e); Logger.Error(e, "Exception occured while invoking completion delegate.");
} }
} }

@ -35,6 +35,7 @@ using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Grpc.Core.Logging;
using Grpc.Core.Utils; using Grpc.Core.Utils;
namespace Grpc.Core.Internal namespace Grpc.Core.Internal
@ -45,6 +46,8 @@ namespace Grpc.Core.Internal
internal class CompletionRegistry internal class CompletionRegistry
{ {
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<CompletionRegistry>();
readonly GrpcEnvironment environment; readonly GrpcEnvironment environment;
readonly ConcurrentDictionary<IntPtr, OpCompletionDelegate> dict = new ConcurrentDictionary<IntPtr, OpCompletionDelegate>(); readonly ConcurrentDictionary<IntPtr, OpCompletionDelegate> dict = new ConcurrentDictionary<IntPtr, OpCompletionDelegate>();
@ -81,7 +84,7 @@ namespace Grpc.Core.Internal
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Exception occured while invoking completion delegate: " + e); Logger.Error(e, "Exception occured while invoking completion delegate.");
} }
finally finally
{ {

@ -36,7 +36,7 @@ using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Grpc.Core.Internal; using Grpc.Core.Logging;
namespace Grpc.Core.Internal namespace Grpc.Core.Internal
{ {
@ -45,6 +45,8 @@ namespace Grpc.Core.Internal
/// </summary> /// </summary>
internal class GrpcThreadPool internal class GrpcThreadPool
{ {
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<GrpcThreadPool>();
readonly GrpcEnvironment environment; readonly GrpcEnvironment environment;
readonly object myLock = new object(); readonly object myLock = new object();
readonly List<Thread> threads = new List<Thread>(); readonly List<Thread> threads = new List<Thread>();
@ -82,7 +84,7 @@ namespace Grpc.Core.Internal
{ {
cq.Shutdown(); cq.Shutdown();
Console.WriteLine("Waiting for GRPC threads to finish."); Logger.Info("Waiting for GRPC threads to finish.");
foreach (var thread in threads) foreach (var thread in threads)
{ {
thread.Join(); thread.Join();
@ -129,12 +131,12 @@ namespace Grpc.Core.Internal
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Exception occured while invoking completion delegate: " + e); Logger.Error(e, "Exception occured while invoking completion delegate");
} }
} }
} }
while (ev.type != GRPCCompletionType.Shutdown); while (ev.type != GRPCCompletionType.Shutdown);
Console.WriteLine("Completion queue has shutdown successfully, thread " + Thread.CurrentThread.Name + " exiting."); Logger.Info("Completion queue has shutdown successfully, thread {0} exiting.", Thread.CurrentThread.Name);
} }
} }
} }

@ -44,30 +44,26 @@ namespace Grpc.Core.Internal
/// <summary> /// <summary>
/// Logs from gRPC C core library can get lost if your application is not a console app. /// Logs from gRPC C core library can get lost if your application is not a console app.
/// This class allows redirection of logs to arbitrary destination. /// This class allows redirection of logs to gRPC logger.
/// </summary> /// </summary>
internal static class GrpcLog internal static class NativeLogRedirector
{ {
static object staticLock = new object(); static object staticLock = new object();
static GprLogDelegate writeCallback; static GprLogDelegate writeCallback;
static TextWriter dest;
[DllImport("grpc_csharp_ext.dll")] [DllImport("grpc_csharp_ext.dll")]
static extern void grpcsharp_redirect_log(GprLogDelegate callback); static extern void grpcsharp_redirect_log(GprLogDelegate callback);
/// <summary> /// <summary>
/// Sets text writer as destination for logs from native gRPC C core library. /// Redirects logs from native gRPC C core library to a general logger.
/// Only first invocation has effect.
/// </summary> /// </summary>
/// <param name="textWriter"></param> public static void Redirect()
public static void RedirectNativeLogs(TextWriter textWriter)
{ {
lock (staticLock) lock (staticLock)
{ {
if (writeCallback == null) if (writeCallback == null)
{ {
writeCallback = new GprLogDelegate(HandleWrite); writeCallback = new GprLogDelegate(HandleWrite);
dest = textWriter;
grpcsharp_redirect_log(writeCallback); grpcsharp_redirect_log(writeCallback);
} }
} }
@ -77,13 +73,30 @@ namespace Grpc.Core.Internal
{ {
try try
{ {
// TODO: DateTime format used here is different than in C core. var logger = GrpcEnvironment.Logger;
dest.WriteLine(string.Format("{0}{1} {2} {3}:{4}: {5}", string severityString = Marshal.PtrToStringAnsi(severityStringPtr);
Marshal.PtrToStringAnsi(severityStringPtr), DateTime.Now, string message = string.Format("{0} {1}:{2}: {3}",
threadId, threadId,
Marshal.PtrToStringAnsi(fileStringPtr), Marshal.PtrToStringAnsi(fileStringPtr),
line, line,
Marshal.PtrToStringAnsi(msgPtr))); Marshal.PtrToStringAnsi(msgPtr));
switch (severityString)
{
case "D":
logger.Debug(message);
break;
case "I":
logger.Info(message);
break;
case "E":
logger.Error(message);
break;
default:
// severity not recognized, default to error.
logger.Error(message);
break;
}
} }
catch (Exception e) catch (Exception e)
{ {

@ -37,6 +37,7 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Grpc.Core.Internal; using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils; using Grpc.Core.Utils;
namespace Grpc.Core.Internal namespace Grpc.Core.Internal
@ -50,6 +51,8 @@ namespace Grpc.Core.Internal
where TRequest : class where TRequest : class
where TResponse : class where TResponse : class
{ {
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<UnaryServerCallHandler<TRequest, TResponse>>();
readonly Method<TRequest, TResponse> method; readonly Method<TRequest, TResponse> method;
readonly UnaryServerMethod<TRequest, TResponse> handler; readonly UnaryServerMethod<TRequest, TResponse> handler;
@ -85,7 +88,7 @@ namespace Grpc.Core.Internal
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Exception occured in handler: " + e); Logger.Error(e, "Exception occured in handler.");
status = HandlerUtils.StatusFromException(e); status = HandlerUtils.StatusFromException(e);
} }
try try
@ -104,6 +107,8 @@ namespace Grpc.Core.Internal
where TRequest : class where TRequest : class
where TResponse : class where TResponse : class
{ {
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<ServerStreamingServerCallHandler<TRequest, TResponse>>();
readonly Method<TRequest, TResponse> method; readonly Method<TRequest, TResponse> method;
readonly ServerStreamingServerMethod<TRequest, TResponse> handler; readonly ServerStreamingServerMethod<TRequest, TResponse> handler;
@ -138,7 +143,7 @@ namespace Grpc.Core.Internal
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Exception occured in handler: " + e); Logger.Error(e, "Exception occured in handler.");
status = HandlerUtils.StatusFromException(e); status = HandlerUtils.StatusFromException(e);
} }
@ -158,6 +163,8 @@ namespace Grpc.Core.Internal
where TRequest : class where TRequest : class
where TResponse : class where TResponse : class
{ {
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<ClientStreamingServerCallHandler<TRequest, TResponse>>();
readonly Method<TRequest, TResponse> method; readonly Method<TRequest, TResponse> method;
readonly ClientStreamingServerMethod<TRequest, TResponse> handler; readonly ClientStreamingServerMethod<TRequest, TResponse> handler;
@ -196,7 +203,7 @@ namespace Grpc.Core.Internal
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Exception occured in handler: " + e); Logger.Error(e, "Exception occured in handler.");
status = HandlerUtils.StatusFromException(e); status = HandlerUtils.StatusFromException(e);
} }
@ -216,6 +223,8 @@ namespace Grpc.Core.Internal
where TRequest : class where TRequest : class
where TResponse : class where TResponse : class
{ {
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<DuplexStreamingServerCallHandler<TRequest, TResponse>>();
readonly Method<TRequest, TResponse> method; readonly Method<TRequest, TResponse> method;
readonly DuplexStreamingServerMethod<TRequest, TResponse> handler; readonly DuplexStreamingServerMethod<TRequest, TResponse> handler;
@ -246,7 +255,7 @@ namespace Grpc.Core.Internal
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Exception occured in handler: " + e); Logger.Error(e, "Exception occured in handler.");
status = HandlerUtils.StatusFromException(e); status = HandlerUtils.StatusFromException(e);
} }
try try

@ -0,0 +1,103 @@
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
namespace Grpc.Core.Logging
{
/// <summary>Logger that logs to System.Console.</summary>
public class ConsoleLogger : ILogger
{
readonly Type forType;
readonly string forTypeString;
public ConsoleLogger() : this(null)
{
}
private ConsoleLogger(Type forType)
{
this.forType = forType;
this.forTypeString = forType != null ? forType.FullName + " " : "";
}
public ILogger ForType<T>()
{
if (typeof(T) == forType)
{
return this;
}
return new ConsoleLogger(typeof(T));
}
public void Debug(string message, params object[] formatArgs)
{
Log("D", message, formatArgs);
}
public void Info(string message, params object[] formatArgs)
{
Log("I", message, formatArgs);
}
public void Warning(string message, params object[] formatArgs)
{
Log("W", message, formatArgs);
}
public void Warning(Exception exception, string message, params object[] formatArgs)
{
Log("W", message + " " + exception, formatArgs);
}
public void Error(string message, params object[] formatArgs)
{
Log("E", message, formatArgs);
}
public void Error(Exception exception, string message, params object[] formatArgs)
{
Log("E", message + " " + exception, formatArgs);
}
private void Log(string severityString, string message, object[] formatArgs)
{
Console.Error.WriteLine("{0}{1} {2}{3}",
severityString,
DateTime.Now,
forTypeString,
string.Format(message, formatArgs));
}
}
}

@ -0,0 +1,57 @@
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
namespace Grpc.Core.Logging
{
/// <summary>For logging messages.</summary>
public interface ILogger
{
/// <summary>Returns a logger associated with the specified type.</summary>
ILogger ForType<T>();
void Debug(string message, params object[] formatArgs);
void Info(string message, params object[] formatArgs);
void Warning(string message, params object[] formatArgs);
void Warning(Exception exception, string message, params object[] formatArgs);
void Error(string message, params object[] formatArgs);
void Error(Exception exception, string message, params object[] formatArgs);
}
}

@ -38,6 +38,7 @@ using System.Diagnostics;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading.Tasks; using System.Threading.Tasks;
using Grpc.Core.Internal; using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils; using Grpc.Core.Utils;
namespace Grpc.Core namespace Grpc.Core
@ -52,6 +53,8 @@ namespace Grpc.Core
/// </summary> /// </summary>
public const int PickUnusedPort = 0; public const int PickUnusedPort = 0;
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Server>();
readonly GrpcEnvironment environment; readonly GrpcEnvironment environment;
readonly List<ChannelOption> options; readonly List<ChannelOption> options;
readonly ServerSafeHandle handle; readonly ServerSafeHandle handle;
@ -233,7 +236,7 @@ namespace Grpc.Core
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Exception while handling RPC: " + e); Logger.Warning(e, "Exception while handling RPC.");
} }
} }

@ -46,13 +46,15 @@ namespace Grpc.Core.Utils
/// </summary> /// </summary>
public static void RunBenchmark(int warmupIterations, int benchmarkIterations, Action action) public static void RunBenchmark(int warmupIterations, int benchmarkIterations, Action action)
{ {
Console.WriteLine("Warmup iterations: " + warmupIterations); var logger = GrpcEnvironment.Logger;
logger.Info("Warmup iterations: {0}", warmupIterations);
for (int i = 0; i < warmupIterations; i++) for (int i = 0; i < warmupIterations; i++)
{ {
action(); action();
} }
Console.WriteLine("Benchmark iterations: " + benchmarkIterations); logger.Info("Benchmark iterations: {0}", benchmarkIterations);
var stopwatch = new Stopwatch(); var stopwatch = new Stopwatch();
stopwatch.Start(); stopwatch.Start();
for (int i = 0; i < benchmarkIterations; i++) for (int i = 0; i < benchmarkIterations; i++)
@ -60,8 +62,8 @@ namespace Grpc.Core.Utils
action(); action();
} }
stopwatch.Stop(); stopwatch.Stop();
Console.WriteLine("Elapsed time: " + stopwatch.ElapsedMilliseconds + "ms"); logger.Info("Elapsed time: {0}ms", stopwatch.ElapsedMilliseconds);
Console.WriteLine("Ops per second: " + (int)((double)benchmarkIterations * 1000 / stopwatch.ElapsedMilliseconds)); logger.Info("Ops per second: {0}", (int)((double)benchmarkIterations * 1000 / stopwatch.ElapsedMilliseconds));
} }
} }
} }

@ -62,7 +62,7 @@ namespace Grpc.IntegrationTesting
File.ReadAllText(TestCredentials.ServerCertChainPath), File.ReadAllText(TestCredentials.ServerCertChainPath),
File.ReadAllText(TestCredentials.ServerPrivateKeyPath)); File.ReadAllText(TestCredentials.ServerPrivateKeyPath));
var serverCredentials = new SslServerCredentials(new [] { keyCertPair }, rootCert); var serverCredentials = new SslServerCredentials(new[] { keyCertPair }, rootCert);
var clientCredentials = new SslCredentials(rootCert, keyCertPair); var clientCredentials = new SslCredentials(rootCert, keyCertPair);
server = new Server(); server = new Server();
@ -93,6 +93,5 @@ namespace Grpc.IntegrationTesting
var response = client.UnaryCall(SimpleRequest.CreateBuilder().SetResponseSize(10).Build()); var response = client.UnaryCall(SimpleRequest.CreateBuilder().SetResponseSize(10).Build());
Assert.AreEqual(10, response.Payload.Body.Length); Assert.AreEqual(10, response.Payload.Body.Length);
} }
} }
} }

Loading…
Cancel
Save