is it possible to style a string in a special way?
modern-nm opened this issue · comments
Hi, i trying to write some logs. All logs written by other soft and have structure like:
Entries:
- author: JustKekc
changes: - {message: Количество кувшинов с химикатами в ХимкоМате увеличилось вдвое., type: Tweak}
- {message: Изменения в дефибрилляторах; Обычный лечит 20 удушья вместо 40. Высоковольтный теперь за удар лечит 45 удушья и наносит 25 электрических повреждений. Мобильный дефибриллятор более не требует заряда однако время между ударами слегка повышено., type: Tweak}
- {message: Изменение иконки патологоанатома., type: Tweak}
- {message: Исправление недочёта на текстурке чёрной одежды патологоанатома., type: Fix}
- {message: Финансовое положение патологоанатома исправлено; теперь он спавнится с 500 кредитами в сумке как и остальные роли., type: Fix}
id: 55695 #костыль отображения в Обновлениях
time: '2024-02-27T22:08:00.0000000+00:00'
It deserializes to my objects correct. But i have a problem with writing log back to file. Structure of file written by me looks like:
Entries:
- author: author
changes:- type: Add
message: >2
Добавлено веселье! - type: Remove
message: >2
Убрано веселье! - type: Tweak
message: >2
Изменено веселье! - type: Fix
message: >2
Исправлено веселье!
id: 1
time: 2024-03-18T19:13:05.8268631+03:00
- type: Add
It's unreadable. Can i make yamldotnet serializer to write yaml string like first example?
I think the closest you could get right now is serialize as json. It would wrap everything in quotes though. However most log aggregators can easily read json.
I just figured this out for you, using a custom event emitter you can set the style of the mapping to flow.
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.EventEmitters;
var serializer = new SerializerBuilder()
.WithEventEmitter(inner => new MappingNodeEventEmitter(inner), where => where.OnBottom())
.Build();
var test = new Log
{
Author = "test",
Changes = new[] {
new Change{
Message = "Test1",
Type = "Tweak"
},
new Change{
Message = "Test2",
Type = "Tweak"
}
}
};
var serialized = serializer.Serialize(test);
Console.WriteLine(serialized);
class MappingNodeEventEmitter : ChainedEventEmitter
{
public MappingNodeEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter)
{
}
public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter)
{
if (eventInfo.Source.StaticType == typeof(Change))
{
eventInfo.Style = MappingStyle.Flow;
}
base.Emit(eventInfo, emitter);
}
}
class Log
{
public string Author { get; set; }
public Change[] Changes { get; set; }
}
class Change
{
public string Message { get; set; }
public string Type { get; set; }
}
Results in
Author: test
Changes:
- {Message: Test1, Type: Tweak}
- {Message: Test2, Type: Tweak}
This is just what i needed. I already got on the trail of EventEmitter, but I still didn't understand how I could achieve such a result until you showed up. I really appreciate your help, @EdwardCooke .