Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

is it possible to style a string in a special way? #916

Closed
modern-nm opened this issue Mar 18, 2024 · 3 comments
Closed

is it possible to style a string in a special way? #916

modern-nm opened this issue Mar 18, 2024 · 3 comments

Comments

@modern-nm
Copy link

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

It's unreadable. Can i make yamldotnet serializer to write yaml string like first example?

@EdwardCooke
Copy link
Collaborator

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.

@EdwardCooke
Copy link
Collaborator

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}

@modern-nm
Copy link
Author

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 .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants