Skip to content

Commit

Permalink
Start implementing JSON logging
Browse files Browse the repository at this point in the history
  • Loading branch information
BenoitGeslain committed Feb 23, 2024
1 parent 10698f4 commit 7bec35a
Showing 1 changed file with 50 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Text.Json;

using CsvHelper;
using CsvHelper.Configuration;
Expand All @@ -11,6 +12,7 @@
using VHToolkit.Redirection;
using VHToolkit.Redirection.BodyRedirection;
using VHToolkit.Redirection.WorldRedirection;
using Newtonsoft.Json;

namespace VHToolkit.Logging
{
Expand Down Expand Up @@ -70,7 +72,7 @@ public RedirectionDataMap() {
}

/// <summary>
/// This class handles the logging behavior at execution time.
/// This class handles the CSV logging behavior at execution time.
/// </summary>
public class Logging : MonoBehaviour {

Expand Down Expand Up @@ -119,4 +121,51 @@ void writeHeaders<Data, DataMap>(out List<Data> records) where DataMap : ClassMa
writeHeaders<RedirectionData, RedirectionDataMap>(out records);
}
}

public class JsonLogging : MonoBehaviour
{

public string pathToFile = "LoggedData\\";
[SerializeField] private string fileNamePrefix;
private string fileName;
private readonly int bufferSize = 10; // number of records kept before writing to disk

private List<RedirectionData> records = new();
private readonly CsvConfiguration config = new(CultureInfo.InvariantCulture) { HasHeaderRecord = false, MemberTypes = MemberTypes.Fields };

private Interaction script;

private void Start()
{
CreateNewFile();
script = GetComponent<Interaction>();
}

private void Update()
{
void writeRecords<Data, DataMap>(List<Data> records) where DataMap : ClassMap<Data>
{
if (records.Count > bufferSize)
{
using var writer = new StreamWriter(fileName, append: true);
using var csv = new CsvWriter(writer, config);
foreach (var record in records) {
writer.WriteLine(JsonConvert.SerializeObject(record));
}
records.Clear();
}
}

records.Add(new RedirectionData(script));
writeRecords<RedirectionData, RedirectionDataMap>(records);
}

public void CreateNewFile()
{
fileName = $"{pathToFile}{fileNamePrefix}{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.json";
using StreamWriter writer = new(fileName);
using CsvWriter csv = new(writer, CultureInfo.InvariantCulture);
records = new List<RedirectionData>();
}
}
}

0 comments on commit 7bec35a

Please sign in to comment.