Skip to content

Commit

Permalink
adding logging extension
Browse files Browse the repository at this point in the history
  • Loading branch information
slorello89 committed Jan 17, 2020
1 parent 3b0d3c7 commit a0ede24
Show file tree
Hide file tree
Showing 5 changed files with 128 additions and 5 deletions.
17 changes: 12 additions & 5 deletions Nexmo.Api/Configuration.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Nexmo.Api.Logging;
using Nexmo.Api.Request;
using System;
using System.Collections.Generic;
using System.Net.Http;

namespace Nexmo.Api
{
public sealed class Configuration
{
const string LOGGER_CATEGORY = "Nexmo.Api.Configuration";
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Configuration()
Expand All @@ -17,6 +19,7 @@ static Configuration()

private Configuration()
{
var logger = Api.Logger.LogProvider.GetLogger(LOGGER_CATEGORY);
var builder = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
Expand Down Expand Up @@ -51,15 +54,19 @@ private Configuration()

if (authCapabilities.Count == 0)
{
logger.LogInformation("No authentication found via configuration. Remember to provide your own.");
//TODO Remove Depricated Logger call
Logger.Info("No authentication found via configuration. Remember to provide your own.");
}
else
{
logger.LogInformation("Available authentication: {0}", string.Join(",", authCapabilities));
//TODO Remove Depricated Logger call
Logger.Info("Available authentication: {0}", string.Join(",", authCapabilities));
}
}

private static readonly ILog Logger = LogProvider.For<Configuration>();
private static readonly ILog Logger = Api.Logging.LogProvider.For<Configuration>();

public static Configuration Instance { get; } = new Configuration();

Expand Down
27 changes: 27 additions & 0 deletions Nexmo.Api/Logger/LogProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System;
namespace Nexmo.Api.Logger
{
public static class LogProvider
{
private static IDictionary<string, ILogger> _loggers = new Dictionary<string, ILogger>();
private static ILoggerFactory _loggerFactory = new LoggerFactory();

public static void SetLogFactory(ILoggerFactory factory)
{
_loggerFactory.Dispose();
_loggerFactory = factory;
_loggers.Clear();
}

public static ILogger GetLogger(string category)
{
if (!_loggers.ContainsKey(category))
{
_loggers[category] = _loggerFactory.CreateLogger(category);
}
return _loggers[category];
}
}
}
28 changes: 28 additions & 0 deletions Nexmo.Api/PemParse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ THE SOFTWARE.
using System.Security.Cryptography;
using System.Text;
using Nexmo.Api.Logging;
using Microsoft.Extensions.Logging;

namespace Nexmo.Api
{
Expand All @@ -68,21 +69,31 @@ public class PemParse

private static readonly ILog Logger = LogProvider.For<PemParse>();

private const string LOGGER_CATEGORY = "Nexmo.Api.PemParse";

public static RSA DecodePEMKey(string pemstr)
{
var logger = Api.Logger.LogProvider.GetLogger(LOGGER_CATEGORY);
pemstr = pemstr.Trim();

var isPkcs1 = pemstr.StartsWith(pkcs1privheader) && pemstr.EndsWith(pkcs1privfooter);
var isPkcs8 = pemstr.StartsWith(pkcs8privheader) && pemstr.EndsWith(pkcs8privfooter);
if (!(isPkcs1 || isPkcs8))
{
logger.LogError("App private key is not in PKCS#1 or PKCS#8 format!");

//TODO remove deprecated Log on new major version
Logger.Error("App private key is not in PKCS#1 or PKCS#8 format!");

return null;
}

var pemprivatekey = DecodeOpenSSLPrivateKey(pemstr);
if (pemprivatekey != null)
return DecodeRSAPrivateKey(pemprivatekey, isPkcs8);
logger.LogError("App private key failed decode!");

//TODO remove deprecated Log on new major version
Logger.Error("App private key failed decode!");
return null;
}
Expand Down Expand Up @@ -164,6 +175,7 @@ private static byte[] DecodeOpenSSLPrivateKey(string instr)

public static RSA DecodeRSAPrivateKey(byte[] privkey, bool isPkcs8)
{
var logger = Api.Logger.LogProvider.GetLogger(LOGGER_CATEGORY);
byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

// --------- Set up stream to decode the asn.1 encoded RSA private key ------
Expand All @@ -182,19 +194,29 @@ public static RSA DecodeRSAPrivateKey(byte[] privkey, bool isPkcs8)
binr.ReadInt16(); //advance 2 bytes
else
{
logger.LogError("RSA decode fail: Expected sequence");

//TODO: remove deprecated Log on new major version
Logger.Error("RSA decode fail: Expected sequence");
return null;
}

twobytes = binr.ReadUInt16();
if (twobytes != 0x0102) //version number
{

logger.LogError("RSA decode fail: Version number mismatch");

//TODO: remove deprecated Log on new major version
Logger.Error("RSA decode fail: Version number mismatch");
return null;
}
bt = binr.ReadByte();
if (bt != 0x00)
{
logger.LogError("RSA decode fail: 00 read fail");

//TODO: remove deprecated Log on new major version
Logger.Error("RSA decode fail: 00 read fail");
return null;
}
Expand All @@ -205,6 +227,9 @@ public static RSA DecodeRSAPrivateKey(byte[] privkey, bool isPkcs8)
bt = binr.ReadByte();
if (bt != 0x30)
{
logger.LogError("RSA decode fail: PKCS#8 expected sequence");

//TODO: remove deprecated Log on new major version
Logger.Error("RSA decode fail: PKCS#8 expected sequence");
return null;
}
Expand Down Expand Up @@ -271,6 +296,9 @@ public static RSA DecodeRSAPrivateKey(byte[] privkey, bool isPkcs8)
}
catch (Exception ex)
{
logger.LogError($"DecodeRSAPrivateKey fail: {ex.Message}, {ex.InnerException?.Message}");

//TODO: remove deprecated Log on new major version
Logger.Error($"DecodeRSAPrivateKey fail: {ex.Message}, {ex.InnerException?.Message}");
return null;
}
Expand Down
39 changes: 39 additions & 0 deletions Nexmo.Api/Request/ApiRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System.Net.Http;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.Logging;

namespace Nexmo.Api.Request
{
Expand All @@ -20,6 +21,7 @@ namespace Nexmo.Api.Request
public static class ApiRequest
{
private static readonly ILog Logger = LogProvider.GetLogger(typeof(ApiRequest), "Nexmo.Api.Request.ApiRequest");
const string LOGGER_CATEGORY = "Nexmo.Api.Request.ApiRequest";

private static StringBuilder BuildQueryString(IDictionary<string, string> parameters, Credentials creds = null)
{
Expand Down Expand Up @@ -146,6 +148,7 @@ internal static string DoRequest(Uri uri, object parameters, Credentials creds =

internal static string DoRequest(Uri uri, Credentials creds)
{
var logger = Api.Logger.LogProvider.GetLogger(LOGGER_CATEGORY);
var apiKey = (creds?.ApiKey ?? Configuration.Instance.Settings["appSettings:Nexmo.api_key"])?.ToLower();
var apiSecret = creds?.ApiSecret ?? Configuration.Instance.Settings["appSettings:Nexmo.api_secret"];
var req = new HttpRequestMessage
Expand All @@ -166,12 +169,18 @@ internal static string DoRequest(Uri uri, Credentials creds)

using (LogProvider.OpenMappedContext("ApiRequest.DoRequest",uri.GetHashCode()))
{
logger.LogDebug($"GET {uri}");

//TODO: Remove deprecated logger
Logger.Debug($"GET {uri}");
var sendTask = Configuration.Instance.Client.SendAsync(req);
sendTask.Wait();

if (!sendTask.Result.IsSuccessStatusCode)
{
logger.LogError($"FAIL: {sendTask.Result.StatusCode}");

//TODO: Remove deprecated logger
Logger.Error($"FAIL: {sendTask.Result.StatusCode}");

if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"],
Expand All @@ -189,6 +198,9 @@ internal static string DoRequest(Uri uri, Credentials creds)
{
json = sr.ReadToEnd();
}
logger.LogDebug(json);

//TODO: Remove Deprecated logger
Logger.Debug(json);
return json;
}
Expand All @@ -205,6 +217,7 @@ internal static string DoRequest(Uri uri, Credentials creds)
/// <returns></returns>
public static NexmoResponse DoRequest(string method, Uri uri, Dictionary<string, string> parameters, Credentials creds = null)
{
var logger = Api.Logger.LogProvider.GetLogger(LOGGER_CATEGORY);
var sb = new StringBuilder();
// if parameters is null, assume that key and secret have been taken care of
if (null != parameters)
Expand All @@ -225,12 +238,18 @@ public static NexmoResponse DoRequest(string method, Uri uri, Dictionary<string,

using (LogProvider.OpenMappedContext("ApiRequest.DoRequest",uri.GetHashCode()))
{
logger.LogDebug($"{method} {uri} {sb}");

//TODO: Remove Deprecated Logger
Logger.Debug($"{method} {uri} {sb}");
var sendTask = Configuration.Instance.Client.SendAsync(req);
sendTask.Wait();

if (!sendTask.Result.IsSuccessStatusCode)
{
logger.LogError($"FAIL: {sendTask.Result.StatusCode}");

//TODO: Remove Deprecated Logger
Logger.Error($"FAIL: {sendTask.Result.StatusCode}");

if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"],
Expand All @@ -252,6 +271,9 @@ public static NexmoResponse DoRequest(string method, Uri uri, Dictionary<string,
{
json = sr.ReadToEnd();
}
logger.LogDebug(json);

//TODO: Remove Deprecated Logger
Logger.Debug(json);
return new NexmoResponse
{
Expand All @@ -263,6 +285,7 @@ public static NexmoResponse DoRequest(string method, Uri uri, Dictionary<string,

public static NexmoResponse DoRequest(string method, Uri uri, object requestBody, Credentials creds = null)
{
var logger = Api.Logger.LogProvider.GetLogger(LOGGER_CATEGORY);
var sb = new StringBuilder();
var parameters = new Dictionary<string, string>();
sb = BuildQueryString(parameters, creds);
Expand All @@ -279,13 +302,19 @@ public static NexmoResponse DoRequest(string method, Uri uri, object requestBody

using (LogProvider.OpenMappedContext("ApiRequest.DoRequest", uri.GetHashCode()))
{
logger.LogDebug($"{method} {uri} {sb}");

//TODO: Remove Deprecated logger
Logger.Debug($"{method} {uri} {sb}");
var sendTask = Configuration.Instance.Client.SendAsync(req);
sendTask.Wait();

if (!sendTask.Result.IsSuccessStatusCode)
{

logger.LogError($"FAIL: {sendTask.Result.StatusCode}");

//TODO: Remove Deprecated Logger
Logger.Error($"FAIL: {sendTask.Result.StatusCode}");

if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"],
Expand All @@ -307,6 +336,9 @@ public static NexmoResponse DoRequest(string method, Uri uri, object requestBody
{
jsonResult = sr.ReadToEnd();
}
logger.LogDebug(jsonResult);

//TODO: Remove Deprecated Logger
Logger.Debug(jsonResult);
return new NexmoResponse
{
Expand All @@ -318,6 +350,7 @@ public static NexmoResponse DoRequest(string method, Uri uri, object requestBody

internal static HttpResponseMessage DoRequestJwt(Uri uri, Credentials creds)
{
var logger = Api.Logger.LogProvider.GetLogger(LOGGER_CATEGORY);
var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"];
var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"];

Expand All @@ -334,12 +367,18 @@ internal static HttpResponseMessage DoRequestJwt(Uri uri, Credentials creds)

using (LogProvider.OpenMappedContext("ApiRequest.DoRequestJwt", uri.GetHashCode()))
{
logger.LogDebug($"GET {uri}");

//TODO: Remove Deprecated logger
Logger.Debug($"GET {uri}");
var sendTask = Configuration.Instance.Client.SendAsync(req);
sendTask.Wait();

if (!sendTask.Result.IsSuccessStatusCode)
{
logger.LogError($"FAIL: {sendTask.Result.StatusCode}");

//TODO: Remove Deprecated Logger
Logger.Error($"FAIL: {sendTask.Result.StatusCode}");

if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"],
Expand Down
Loading

0 comments on commit a0ede24

Please # to comment.