diff --git a/Visuo-haptic Toolkit/Assets/Visuo-Haptic Toolkit/Scripts/Logging/Logging.cs b/Visuo-haptic Toolkit/Assets/Visuo-Haptic Toolkit/Scripts/Logging/Logging.cs index c241c411..2e029d13 100644 --- a/Visuo-haptic Toolkit/Assets/Visuo-Haptic Toolkit/Scripts/Logging/Logging.cs +++ b/Visuo-haptic Toolkit/Assets/Visuo-Haptic Toolkit/Scripts/Logging/Logging.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Globalization; +using System.Text.Json; using CsvHelper; using CsvHelper.Configuration; @@ -11,6 +12,7 @@ using VHToolkit.Redirection; using VHToolkit.Redirection.BodyRedirection; using VHToolkit.Redirection.WorldRedirection; +using Newtonsoft.Json; namespace VHToolkit.Logging { @@ -70,7 +72,7 @@ public RedirectionDataMap() { } /// - /// This class handles the logging behavior at execution time. + /// This class handles the CSV logging behavior at execution time. /// public class Logging : MonoBehaviour { @@ -119,4 +121,51 @@ void writeHeaders(out List records) where DataMap : ClassMa writeHeaders(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 records = new(); + private readonly CsvConfiguration config = new(CultureInfo.InvariantCulture) { HasHeaderRecord = false, MemberTypes = MemberTypes.Fields }; + + private Interaction script; + + private void Start() + { + CreateNewFile(); + script = GetComponent(); + } + + private void Update() + { + void writeRecords(List records) where DataMap : ClassMap + { + 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(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(); + } + } } \ No newline at end of file