Skip to content

Commit

Permalink
feat: add ILogger interface(#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tochemey authored Nov 10, 2024
1 parent 9e886a5 commit 8ac7f14
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 85 deletions.
41 changes: 41 additions & 0 deletions NetCore8583/ILogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.Diagnostics;

namespace NetCore8583;

/// <summary>
/// ILogger is an interface that will be implemented
/// </summary>
public interface ILogger
{
/// <summary>
/// Info log info message
/// </summary>
/// <param name="messageTemplate">the message template</param>
void Info(string messageTemplate);

/// <summary>
/// Debug log in debug mode
/// </summary>
/// <param name="messageTemplate">the message template</param>
void Debug(string messageTemplate);

/// <summary>
/// Warning logs message in warning mode
/// </summary>
/// <param name="messageTemplate">the message template</param>
void Warning(string messageTemplate);

/// <summary>
/// Error log error message
/// </summary>
/// <param name="messageTemplate">the message template</param>
void Error(string messageTemplate);

/// <summary>
/// Error log an Exception with a custom error message
/// </summary>
/// <param name="exception">the exception</param>
/// <param name="messageTemplate">the message template</param>
void Error(Exception exception, string messageTemplate);
}
50 changes: 18 additions & 32 deletions NetCore8583/MessageFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@
using System.Text;
using NetCore8583.Parse;
using NetCore8583.Util;
using Serilog;
using Serilog.Core;
using Serilog.Events;


namespace NetCore8583
{
Expand Down Expand Up @@ -37,11 +35,7 @@ public class MessageFactory<T> where T : IsoMessage
/// The ISO header to be included in each message type
/// </summary>
private readonly Dictionary<int, string> _isoHeaders = new Dictionary<int, string>();

private readonly Logger _logger = new LoggerConfiguration().MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console().CreateLogger();


/// <summary>
/// This map stores the message template for each message type.
Expand Down Expand Up @@ -256,12 +250,13 @@ public T CreateResponse(T request, bool copyAllFields = true)
/// <summary>
/// Sets the timezone for the specified FieldParseInfo, if it's needed for parsing dates.
/// </summary>
/// <param name="messageType"></param>
/// <param name="field"></param>
/// <param name="tz"></param>
/// <param name="messageType">the message type</param>
/// <param name="field">the given field</param>
/// <param name="tz">the timezone information</param>
/// <param name="logger">a custom logger</param>
public void SetTimezoneForParseGuide(int messageType,
int field,
TimeZoneInfo tz)
TimeZoneInfo tz, ILogger logger = null)
{
var guide = ParseMap[messageType];
var fpi = guide?[field];
Expand All @@ -271,9 +266,7 @@ public void SetTimezoneForParseGuide(int messageType,
return;
}

_logger.Warning("Field {@Field} for message type {@MessageType} is not for dates, cannot set timezone",
field,
messageType);
logger?.Warning($"Field {field} for message type {messageType} is not for dates, cannot set timezone");
}

/// <summary>
Expand All @@ -290,10 +283,11 @@ public void SetTimezoneForParseGuide(int messageType,
/// type is located, which is also the length of the ISO header.
/// </param>
/// <param name="binaryIsoHeader"></param>
/// <param name="logger">the custom logger</param>
/// <returns>The parsed message.</returns>
public T ParseMessage(sbyte[] buf,
int isoHeaderLength,
bool binaryIsoHeader = false)
bool binaryIsoHeader = false, ILogger logger = null)
{
var minlength = isoHeaderLength + (UseBinaryMessages ? 2 : 4) +
(UseBinaryBitmap || UseBinaryMessages ? 8 : 16);
Expand Down Expand Up @@ -514,7 +508,7 @@ public T ParseMessage(sbyte[] buf,
var index = ParseOrder[type];
if (index == null)
{
_logger.Error(
logger?.Error(
$"ISO8583 MessageFactory has no parsing guide for message type {type:X} [{buf.ToString(0, buf.Length, _encoding)}]");
throw new Exception(
$"ISO8583 MessageFactory has no parsing guide for message type {type:X} [{buf.ToString(0, buf.Length, _encoding)}]");
Expand All @@ -525,8 +519,7 @@ public T ParseMessage(sbyte[] buf,
for (var i = 1; i < bs.Length; i++)
if (bs.Get(i) && !index.Contains(i + 1))
{
_logger.Warning("ISO8583 MessageFactory cannot parse field {Field}: unspecified in parsing guide",
i + 1);
logger?.Warning($"ISO8583 MessageFactory cannot parse field {i+1}: unspecified in parsing guide");
abandon = true;
}

Expand All @@ -540,16 +533,12 @@ public T ParseMessage(sbyte[] buf,
if (!bs.Get(i - 1)) continue;
if (IgnoreLast && pos >= buf.Length && i == index[^1])
{
_logger.Warning("Field {@Index} is not really in the message even though it's in the bitmap",
i);

bs.Set(i - 1,
false);
logger?.Warning($"Field {i} is not really in the message even though it's in the bitmap");
bs.Set(i - 1, false);
}
else
{
var decoder = fpi.Decoder ?? GetCustomField(i);

var val = fpi.ParseBinary(i,
buf,
pos,
Expand Down Expand Up @@ -587,11 +576,8 @@ public T ParseMessage(sbyte[] buf,
if (bs.Get(i - 1))
if (IgnoreLast && pos >= buf.Length && i == index[^1])
{
_logger.Warning(
"Field {@FieldId} is not really in the message even though it's in the bitmap",
i);
bs.Set(i - 1,
false);
logger?.Warning($"Field {i} is not really in the message even though it's in the bitmap");
bs.Set(i - 1, false);
}
else
{
Expand Down Expand Up @@ -738,7 +724,7 @@ public T GetMessageTemplate(int type)
}

public void SetParseMap(int type,
Dictionary<int, FieldParseInfo> map)
Dictionary<int, FieldParseInfo> map, ILogger logger = null)
{
if (ParseMap.ContainsKey(type)) ParseMap[type] = map;
else
Expand All @@ -748,7 +734,7 @@ public void SetParseMap(int type,
var index = new List<int>();
index.AddRange(map.Keys);
index.Sort();
_logger.Warning($"ISO8583 MessageFactory adding parse map for type {type:X} with fields {index}");
logger?.Warning($"ISO8583 MessageFactory adding parse map for type {type:X} with fields {index}");

if (ParseOrder.ContainsKey(type)) ParseOrder[type] = index;
else
Expand Down
5 changes: 0 additions & 5 deletions NetCore8583/NetCore8583.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,6 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="8.0.2" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.2" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="8.0.0" />
</ItemGroup>

Expand Down
55 changes: 7 additions & 48 deletions NetCore8583/Parse/ConfigParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@
using System.Xml;
using NetCore8583.Codecs;
using NetCore8583.Util;
using Serilog;
using Serilog.Core;
using Serilog.Events;

namespace NetCore8583.Parse
{
Expand All @@ -19,10 +16,6 @@ namespace NetCore8583.Parse
/// </summary>
public static class ConfigParser
{
private static readonly Logger Logger = new LoggerConfiguration().MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console().CreateLogger();

/// <summary>
/// Creates a message factory configured from the default file, which is n8583.xml
Expand Down Expand Up @@ -75,14 +68,6 @@ private static void ParseHeaders<T>(XmlNodeList nodes,
{
var header = elem.ChildNodes.Item(0)?.Value;
var binHeader = "true".Equals(elem.GetAttribute("binary"));
if (Logger.IsEnabled(LogEventLevel.Debug))
{
var binary = binHeader ? "binary" : string.Empty;

Logger.Debug(
$"Adding {binary} ISO8583 header for type {elem.GetAttribute("type")} : {header}");
}

if (binHeader)
mfact.SetBinaryIsoHeader(type, HexCodec.HexDecode(header).ToUint8());
else
Expand All @@ -107,12 +92,6 @@ private static void ParseHeaders<T>(XmlNodeList nodes,
var h = mfact.GetIsoHeader(t2);
if (h == null)
throw new ArgumentException("Header def " + type + " refers to nonexistent header " + t2);
if (Logger.IsEnabled(LogEventLevel.Debug))
Logger.Debug(
"Adding ISO8583 header for type {Type}: {H} (copied from {Ref})",
elem.GetAttribute("type"),
h,
elem.GetAttribute("ref"));
mfact.SetIsoHeader(type, h);
}
}
Expand Down Expand Up @@ -319,7 +298,7 @@ private static FieldParseInfo GetParser<T>(XmlElement f,
}

private static void ParseGuides<T>(XmlNodeList nodes,
MessageFactory<T> mfact) where T : IsoMessage
MessageFactory<T> mfact, ILogger logger = null) where T : IsoMessage
{
List<XmlElement> subs = null;
var guides = new Dictionary<int, Dictionary<int, FieldParseInfo>>();
Expand Down Expand Up @@ -351,7 +330,7 @@ private static void ParseGuides<T>(XmlNodeList nodes,
parseMap.Add(num, GetParser(f, mfact));
}

mfact.SetParseMap(type, parseMap);
mfact.SetParseMap(type, parseMap, logger);

if (guides.ContainsKey(type)) guides[type] = parseMap;
else
Expand Down Expand Up @@ -390,7 +369,7 @@ private static void ParseGuides<T>(XmlNodeList nodes,
child.Add(num, GetParser(f, mfact));
}

mfact.SetParseMap(type, child);
mfact.SetParseMap(type, child, logger);

if (guides.ContainsKey(type)) guides[type] = child;
else
Expand Down Expand Up @@ -443,7 +422,7 @@ private static void Parse<T>(MessageFactory<T> mfact, Stream source) where T : I
}
catch (Exception e)
{
Logger.Error($"ISO8583 Cannot parse XML configuration {e}");
throw new IOException("Error parsing parse XML configuration", e);
}
}

Expand All @@ -460,16 +439,11 @@ public static void ConfigureFromClasspathConfig<T>(MessageFactory<T> mfact, stri
{
var f = AppDomain.CurrentDomain.BaseDirectory + path;
using var fsSource = new FileStream(f, FileMode.Open, FileAccess.Read);
Logger.Debug(
"ISO8583 Parsing config from classpath file {Path}",
path);
Parse(mfact, fsSource);
}
catch (FileNotFoundException)
{
Logger.Warning(
"ISO8583 File not found in classpath: {Path}",
path);
throw new IOException("ISO8583 File not found in classpath: " + path);
}
}

Expand All @@ -488,21 +462,11 @@ public static async Task ConfigureFromUrlAsync<T>(MessageFactory<T> mfact, Uri u
using (client)
{
var stream = await client.GetStreamAsync(url);

Logger.Debug(
"ISO8583 Parsing config from classpath file {Path}",
url.ToString());

Parse(
mfact,
stream);
Parse(mfact, stream);
}
}
catch (Exception)
{
Logger.Warning(
"ISO8583 File not found in classpath: {Path}",
url.ToString());
throw;
}
}
Expand All @@ -522,22 +486,17 @@ public static void ConfigureFromDefault<T>(MessageFactory<T> mfact) where T : Is

if (!File.Exists(configFile))
{
Logger.Warning("ISO8583 config file n8583.xml not found!");
throw new FileNotFoundException("n8583.xml not found!");
}

try
{
using var fsSource = new FileStream(configFile, FileMode.Open, FileAccess.Read);
Logger.Debug(
"ISO8583 Parsing config from classpath file {Path}",
configFile);
Parse(mfact, fsSource);
}
catch (Exception e)
{
Logger.Error("Error while parsing the config file" + e);
throw;
throw new Exception("Error while parsing the config file", e);
}
}
}
Expand Down

0 comments on commit 8ac7f14

Please sign in to comment.