Skip to content

Commit 8ac7f14

Browse files
authored
feat: add ILogger interface(#27)
1 parent 9e886a5 commit 8ac7f14

File tree

4 files changed

+66
-85
lines changed

4 files changed

+66
-85
lines changed

NetCore8583/ILogger.cs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
using System;
2+
using System.Diagnostics;
3+
4+
namespace NetCore8583;
5+
6+
/// <summary>
7+
/// ILogger is an interface that will be implemented
8+
/// </summary>
9+
public interface ILogger
10+
{
11+
/// <summary>
12+
/// Info log info message
13+
/// </summary>
14+
/// <param name="messageTemplate">the message template</param>
15+
void Info(string messageTemplate);
16+
17+
/// <summary>
18+
/// Debug log in debug mode
19+
/// </summary>
20+
/// <param name="messageTemplate">the message template</param>
21+
void Debug(string messageTemplate);
22+
23+
/// <summary>
24+
/// Warning logs message in warning mode
25+
/// </summary>
26+
/// <param name="messageTemplate">the message template</param>
27+
void Warning(string messageTemplate);
28+
29+
/// <summary>
30+
/// Error log error message
31+
/// </summary>
32+
/// <param name="messageTemplate">the message template</param>
33+
void Error(string messageTemplate);
34+
35+
/// <summary>
36+
/// Error log an Exception with a custom error message
37+
/// </summary>
38+
/// <param name="exception">the exception</param>
39+
/// <param name="messageTemplate">the message template</param>
40+
void Error(Exception exception, string messageTemplate);
41+
}

NetCore8583/MessageFactory.cs

Lines changed: 18 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,7 @@
55
using System.Text;
66
using NetCore8583.Parse;
77
using NetCore8583.Util;
8-
using Serilog;
9-
using Serilog.Core;
10-
using Serilog.Events;
8+
119

1210
namespace NetCore8583
1311
{
@@ -37,11 +35,7 @@ public class MessageFactory<T> where T : IsoMessage
3735
/// The ISO header to be included in each message type
3836
/// </summary>
3937
private readonly Dictionary<int, string> _isoHeaders = new Dictionary<int, string>();
40-
41-
private readonly Logger _logger = new LoggerConfiguration().MinimumLevel.Debug()
42-
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
43-
.Enrich.FromLogContext()
44-
.WriteTo.Console().CreateLogger();
38+
4539

4640
/// <summary>
4741
/// This map stores the message template for each message type.
@@ -256,12 +250,13 @@ public T CreateResponse(T request, bool copyAllFields = true)
256250
/// <summary>
257251
/// Sets the timezone for the specified FieldParseInfo, if it's needed for parsing dates.
258252
/// </summary>
259-
/// <param name="messageType"></param>
260-
/// <param name="field"></param>
261-
/// <param name="tz"></param>
253+
/// <param name="messageType">the message type</param>
254+
/// <param name="field">the given field</param>
255+
/// <param name="tz">the timezone information</param>
256+
/// <param name="logger">a custom logger</param>
262257
public void SetTimezoneForParseGuide(int messageType,
263258
int field,
264-
TimeZoneInfo tz)
259+
TimeZoneInfo tz, ILogger logger = null)
265260
{
266261
var guide = ParseMap[messageType];
267262
var fpi = guide?[field];
@@ -271,9 +266,7 @@ public void SetTimezoneForParseGuide(int messageType,
271266
return;
272267
}
273268

274-
_logger.Warning("Field {@Field} for message type {@MessageType} is not for dates, cannot set timezone",
275-
field,
276-
messageType);
269+
logger?.Warning($"Field {field} for message type {messageType} is not for dates, cannot set timezone");
277270
}
278271

279272
/// <summary>
@@ -290,10 +283,11 @@ public void SetTimezoneForParseGuide(int messageType,
290283
/// type is located, which is also the length of the ISO header.
291284
/// </param>
292285
/// <param name="binaryIsoHeader"></param>
286+
/// <param name="logger">the custom logger</param>
293287
/// <returns>The parsed message.</returns>
294288
public T ParseMessage(sbyte[] buf,
295289
int isoHeaderLength,
296-
bool binaryIsoHeader = false)
290+
bool binaryIsoHeader = false, ILogger logger = null)
297291
{
298292
var minlength = isoHeaderLength + (UseBinaryMessages ? 2 : 4) +
299293
(UseBinaryBitmap || UseBinaryMessages ? 8 : 16);
@@ -514,7 +508,7 @@ public T ParseMessage(sbyte[] buf,
514508
var index = ParseOrder[type];
515509
if (index == null)
516510
{
517-
_logger.Error(
511+
logger?.Error(
518512
$"ISO8583 MessageFactory has no parsing guide for message type {type:X} [{buf.ToString(0, buf.Length, _encoding)}]");
519513
throw new Exception(
520514
$"ISO8583 MessageFactory has no parsing guide for message type {type:X} [{buf.ToString(0, buf.Length, _encoding)}]");
@@ -525,8 +519,7 @@ public T ParseMessage(sbyte[] buf,
525519
for (var i = 1; i < bs.Length; i++)
526520
if (bs.Get(i) && !index.Contains(i + 1))
527521
{
528-
_logger.Warning("ISO8583 MessageFactory cannot parse field {Field}: unspecified in parsing guide",
529-
i + 1);
522+
logger?.Warning($"ISO8583 MessageFactory cannot parse field {i+1}: unspecified in parsing guide");
530523
abandon = true;
531524
}
532525

@@ -540,16 +533,12 @@ public T ParseMessage(sbyte[] buf,
540533
if (!bs.Get(i - 1)) continue;
541534
if (IgnoreLast && pos >= buf.Length && i == index[^1])
542535
{
543-
_logger.Warning("Field {@Index} is not really in the message even though it's in the bitmap",
544-
i);
545-
546-
bs.Set(i - 1,
547-
false);
536+
logger?.Warning($"Field {i} is not really in the message even though it's in the bitmap");
537+
bs.Set(i - 1, false);
548538
}
549539
else
550540
{
551541
var decoder = fpi.Decoder ?? GetCustomField(i);
552-
553542
var val = fpi.ParseBinary(i,
554543
buf,
555544
pos,
@@ -587,11 +576,8 @@ public T ParseMessage(sbyte[] buf,
587576
if (bs.Get(i - 1))
588577
if (IgnoreLast && pos >= buf.Length && i == index[^1])
589578
{
590-
_logger.Warning(
591-
"Field {@FieldId} is not really in the message even though it's in the bitmap",
592-
i);
593-
bs.Set(i - 1,
594-
false);
579+
logger?.Warning($"Field {i} is not really in the message even though it's in the bitmap");
580+
bs.Set(i - 1, false);
595581
}
596582
else
597583
{
@@ -738,7 +724,7 @@ public T GetMessageTemplate(int type)
738724
}
739725

740726
public void SetParseMap(int type,
741-
Dictionary<int, FieldParseInfo> map)
727+
Dictionary<int, FieldParseInfo> map, ILogger logger = null)
742728
{
743729
if (ParseMap.ContainsKey(type)) ParseMap[type] = map;
744730
else
@@ -748,7 +734,7 @@ public void SetParseMap(int type,
748734
var index = new List<int>();
749735
index.AddRange(map.Keys);
750736
index.Sort();
751-
_logger.Warning($"ISO8583 MessageFactory adding parse map for type {type:X} with fields {index}");
737+
logger?.Warning($"ISO8583 MessageFactory adding parse map for type {type:X} with fields {index}");
752738

753739
if (ParseOrder.ContainsKey(type)) ParseOrder[type] = index;
754740
else

NetCore8583/NetCore8583.csproj

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,6 @@
2828
</PropertyGroup>
2929

3030
<ItemGroup>
31-
<PackageReference Include="Serilog.AspNetCore" Version="8.0.2" />
32-
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
33-
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
34-
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.2" />
35-
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
3631
<PackageReference Include="System.Text.Encoding.CodePages" Version="8.0.0" />
3732
</ItemGroup>
3833

NetCore8583/Parse/ConfigParser.cs

Lines changed: 7 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,6 @@
77
using System.Xml;
88
using NetCore8583.Codecs;
99
using NetCore8583.Util;
10-
using Serilog;
11-
using Serilog.Core;
12-
using Serilog.Events;
1310

1411
namespace NetCore8583.Parse
1512
{
@@ -19,10 +16,6 @@ namespace NetCore8583.Parse
1916
/// </summary>
2017
public static class ConfigParser
2118
{
22-
private static readonly Logger Logger = new LoggerConfiguration().MinimumLevel.Debug()
23-
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
24-
.Enrich.FromLogContext()
25-
.WriteTo.Console().CreateLogger();
2619

2720
/// <summary>
2821
/// Creates a message factory configured from the default file, which is n8583.xml
@@ -75,14 +68,6 @@ private static void ParseHeaders<T>(XmlNodeList nodes,
7568
{
7669
var header = elem.ChildNodes.Item(0)?.Value;
7770
var binHeader = "true".Equals(elem.GetAttribute("binary"));
78-
if (Logger.IsEnabled(LogEventLevel.Debug))
79-
{
80-
var binary = binHeader ? "binary" : string.Empty;
81-
82-
Logger.Debug(
83-
$"Adding {binary} ISO8583 header for type {elem.GetAttribute("type")} : {header}");
84-
}
85-
8671
if (binHeader)
8772
mfact.SetBinaryIsoHeader(type, HexCodec.HexDecode(header).ToUint8());
8873
else
@@ -107,12 +92,6 @@ private static void ParseHeaders<T>(XmlNodeList nodes,
10792
var h = mfact.GetIsoHeader(t2);
10893
if (h == null)
10994
throw new ArgumentException("Header def " + type + " refers to nonexistent header " + t2);
110-
if (Logger.IsEnabled(LogEventLevel.Debug))
111-
Logger.Debug(
112-
"Adding ISO8583 header for type {Type}: {H} (copied from {Ref})",
113-
elem.GetAttribute("type"),
114-
h,
115-
elem.GetAttribute("ref"));
11695
mfact.SetIsoHeader(type, h);
11796
}
11897
}
@@ -319,7 +298,7 @@ private static FieldParseInfo GetParser<T>(XmlElement f,
319298
}
320299

321300
private static void ParseGuides<T>(XmlNodeList nodes,
322-
MessageFactory<T> mfact) where T : IsoMessage
301+
MessageFactory<T> mfact, ILogger logger = null) where T : IsoMessage
323302
{
324303
List<XmlElement> subs = null;
325304
var guides = new Dictionary<int, Dictionary<int, FieldParseInfo>>();
@@ -351,7 +330,7 @@ private static void ParseGuides<T>(XmlNodeList nodes,
351330
parseMap.Add(num, GetParser(f, mfact));
352331
}
353332

354-
mfact.SetParseMap(type, parseMap);
333+
mfact.SetParseMap(type, parseMap, logger);
355334

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

393-
mfact.SetParseMap(type, child);
372+
mfact.SetParseMap(type, child, logger);
394373

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

@@ -460,16 +439,11 @@ public static void ConfigureFromClasspathConfig<T>(MessageFactory<T> mfact, stri
460439
{
461440
var f = AppDomain.CurrentDomain.BaseDirectory + path;
462441
using var fsSource = new FileStream(f, FileMode.Open, FileAccess.Read);
463-
Logger.Debug(
464-
"ISO8583 Parsing config from classpath file {Path}",
465-
path);
466442
Parse(mfact, fsSource);
467443
}
468444
catch (FileNotFoundException)
469445
{
470-
Logger.Warning(
471-
"ISO8583 File not found in classpath: {Path}",
472-
path);
446+
throw new IOException("ISO8583 File not found in classpath: " + path);
473447
}
474448
}
475449

@@ -488,21 +462,11 @@ public static async Task ConfigureFromUrlAsync<T>(MessageFactory<T> mfact, Uri u
488462
using (client)
489463
{
490464
var stream = await client.GetStreamAsync(url);
491-
492-
Logger.Debug(
493-
"ISO8583 Parsing config from classpath file {Path}",
494-
url.ToString());
495-
496-
Parse(
497-
mfact,
498-
stream);
465+
Parse(mfact, stream);
499466
}
500467
}
501468
catch (Exception)
502469
{
503-
Logger.Warning(
504-
"ISO8583 File not found in classpath: {Path}",
505-
url.ToString());
506470
throw;
507471
}
508472
}
@@ -522,22 +486,17 @@ public static void ConfigureFromDefault<T>(MessageFactory<T> mfact) where T : Is
522486

523487
if (!File.Exists(configFile))
524488
{
525-
Logger.Warning("ISO8583 config file n8583.xml not found!");
526489
throw new FileNotFoundException("n8583.xml not found!");
527490
}
528491

529492
try
530493
{
531494
using var fsSource = new FileStream(configFile, FileMode.Open, FileAccess.Read);
532-
Logger.Debug(
533-
"ISO8583 Parsing config from classpath file {Path}",
534-
configFile);
535495
Parse(mfact, fsSource);
536496
}
537497
catch (Exception e)
538498
{
539-
Logger.Error("Error while parsing the config file" + e);
540-
throw;
499+
throw new Exception("Error while parsing the config file", e);
541500
}
542501
}
543502
}

0 commit comments

Comments
 (0)