aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/core/log.cpp
blob: 4bafd458423e0acf427eed4eb448cdcea5a1f735 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
#include "log.h"
#include "log_settings.h"

#include <library/cpp/monlib/service/pages/templates.h>

static_assert(int(NActors::NLog::PRI_EMERG) == int(::TLOG_EMERG), "expect int(NActors::NLog::PRI_EMERG) == int(::TLOG_EMERG)");
static_assert(int(NActors::NLog::PRI_ALERT) == int(::TLOG_ALERT), "expect int(NActors::NLog::PRI_ALERT) == int(::TLOG_ALERT)");
static_assert(int(NActors::NLog::PRI_CRIT) == int(::TLOG_CRIT), "expect int(NActors::NLog::PRI_CRIT) == int(::TLOG_CRIT)");
static_assert(int(NActors::NLog::PRI_ERROR) == int(::TLOG_ERR), "expect int(NActors::NLog::PRI_ERROR) == int(::TLOG_ERR)");
static_assert(int(NActors::NLog::PRI_WARN) == int(::TLOG_WARNING), "expect int(NActors::NLog::PRI_WARN) == int(::TLOG_WARNING)");
static_assert(int(NActors::NLog::PRI_NOTICE) == int(::TLOG_NOTICE), "expect int(NActors::NLog::PRI_NOTICE) == int(::TLOG_NOTICE)");
static_assert(int(NActors::NLog::PRI_INFO) == int(::TLOG_INFO), "expect int(NActors::NLog::PRI_INFO) == int(::TLOG_INFO)");
static_assert(int(NActors::NLog::PRI_DEBUG) == int(::TLOG_DEBUG), "expect int(NActors::NLog::PRI_DEBUG) == int(::TLOG_DEBUG)");
static_assert(int(NActors::NLog::PRI_TRACE) == int(::TLOG_RESOURCES), "expect int(NActors::NLog::PRI_TRACE) == int(::TLOG_RESOURCES)");

namespace {
    struct TRecordWithNewline {
        ELogPriority Priority;
        TTempBuf Buf;

        TRecordWithNewline(const TLogRecord& rec)
            : Priority(rec.Priority)
            , Buf(rec.Len + 1)
        {
            Buf.Append(rec.Data, rec.Len);
            *Buf.Proceed(1) = '\n';
        }

        operator TLogRecord() const {
            return TLogRecord(Priority, Buf.Data(), Buf.Filled());
        }
    };
}

namespace NActors {

    class TLoggerCounters : public ILoggerMetrics {
    public:
        TLoggerCounters(TIntrusivePtr<NMonitoring::TDynamicCounters> counters)
            : DynamicCounters(counters)
        {
            ActorMsgs_ = DynamicCounters->GetCounter("ActorMsgs", true);
            DirectMsgs_ = DynamicCounters->GetCounter("DirectMsgs", true);
            LevelRequests_ = DynamicCounters->GetCounter("LevelRequests", true);
            IgnoredMsgs_ = DynamicCounters->GetCounter("IgnoredMsgs", true);
            DroppedMsgs_ = DynamicCounters->GetCounter("DroppedMsgs", true);

            AlertMsgs_ = DynamicCounters->GetCounter("AlertMsgs", true);
            EmergMsgs_ = DynamicCounters->GetCounter("EmergMsgs", true);
        }

        ~TLoggerCounters() = default;

        void IncActorMsgs() override {
            ++*ActorMsgs_;
        }
        void IncDirectMsgs() override {
            ++*DirectMsgs_;
        }
        void IncLevelRequests() override {
            ++*LevelRequests_;
        }
        void IncIgnoredMsgs() override {
            ++*IgnoredMsgs_;
        }
        void IncAlertMsgs() override {
            ++*AlertMsgs_;
        }
        void IncEmergMsgs() override {
            ++*EmergMsgs_;
        }
        void IncDroppedMsgs() override {
            DroppedMsgs_->Inc();
        };

        void GetOutputHtml(IOutputStream& str) override {
            HTML(str) {
                DIV_CLASS("row") {
                    DIV_CLASS("col-md-12") {
                        TAG(TH4) {
                            str << "Counters" << Endl;
                        }
                        DynamicCounters->OutputHtml(str);
                    }
                }
            }
        }

    private:
        NMonitoring::TDynamicCounters::TCounterPtr ActorMsgs_;
        NMonitoring::TDynamicCounters::TCounterPtr DirectMsgs_;
        NMonitoring::TDynamicCounters::TCounterPtr LevelRequests_;
        NMonitoring::TDynamicCounters::TCounterPtr IgnoredMsgs_;
        NMonitoring::TDynamicCounters::TCounterPtr AlertMsgs_;
        NMonitoring::TDynamicCounters::TCounterPtr EmergMsgs_;
        // Dropped while the logger backend was unavailable
        NMonitoring::TDynamicCounters::TCounterPtr DroppedMsgs_;

        TIntrusivePtr<NMonitoring::TDynamicCounters> DynamicCounters;
    };

    class TLoggerMetrics : public ILoggerMetrics {
    public:
        TLoggerMetrics(std::shared_ptr<NMonitoring::TMetricRegistry> metrics)
            : Metrics(metrics)
        {
            ActorMsgs_ = Metrics->Rate(NMonitoring::TLabels{{"sensor", "logger.actor_msgs"}});
            DirectMsgs_ = Metrics->Rate(NMonitoring::TLabels{{"sensor", "logger.direct_msgs"}});
            LevelRequests_ = Metrics->Rate(NMonitoring::TLabels{{"sensor", "logger.level_requests"}});
            IgnoredMsgs_ = Metrics->Rate(NMonitoring::TLabels{{"sensor", "logger.ignored_msgs"}});
            DroppedMsgs_ = Metrics->Rate(NMonitoring::TLabels{{"sensor", "logger.dropped_msgs"}});

            AlertMsgs_ = Metrics->Rate(NMonitoring::TLabels{{"sensor", "logger.alert_msgs"}});
            EmergMsgs_ = Metrics->Rate(NMonitoring::TLabels{{"sensor", "logger.emerg_msgs"}});
        }

        ~TLoggerMetrics() = default;

        void IncActorMsgs() override {
            ActorMsgs_->Inc();
        }
        void IncDirectMsgs() override {
            DirectMsgs_->Inc();
        }
        void IncLevelRequests() override {
            LevelRequests_->Inc();
        }
        void IncIgnoredMsgs() override {
            IgnoredMsgs_->Inc();
        }
        void IncAlertMsgs() override {
            AlertMsgs_->Inc();
        }
        void IncEmergMsgs() override {
            EmergMsgs_->Inc();
        }
        void IncDroppedMsgs() override {
            DroppedMsgs_->Inc();
        };

        void GetOutputHtml(IOutputStream& str) override {
            HTML(str) {
                DIV_CLASS("row") {
                    DIV_CLASS("col-md-12") {
                        TAG(TH4) {
                            str << "Metrics" << Endl;
                        }
                        // TODO: Now, TMetricRegistry does not have the GetOutputHtml function
                    }
                }
            }
        }

    private:
        NMonitoring::TRate* ActorMsgs_;
        NMonitoring::TRate* DirectMsgs_;
        NMonitoring::TRate* LevelRequests_;
        NMonitoring::TRate* IgnoredMsgs_;
        NMonitoring::TRate* AlertMsgs_;
        NMonitoring::TRate* EmergMsgs_;
        // Dropped while the logger backend was unavailable
        NMonitoring::TRate* DroppedMsgs_;

        std::shared_ptr<NMonitoring::TMetricRegistry> Metrics;
    };

    TLoggerActor::TLoggerActor(TIntrusivePtr<NLog::TSettings> settings,
                               TAutoPtr<TLogBackend> logBackend,
                               TIntrusivePtr<NMonitoring::TDynamicCounters> counters)
        : TActor(&TLoggerActor::StateFunc)
        , Settings(settings)
        , LogBackend(logBackend.Release())
        , Metrics(std::make_unique<TLoggerCounters>(counters))
    {
    }

    TLoggerActor::TLoggerActor(TIntrusivePtr<NLog::TSettings> settings,
                               std::shared_ptr<TLogBackend> logBackend,
                               TIntrusivePtr<NMonitoring::TDynamicCounters> counters)
        : TActor(&TLoggerActor::StateFunc)
        , Settings(settings)
        , LogBackend(logBackend)
        , Metrics(std::make_unique<TLoggerCounters>(counters))
    {
    }

    TLoggerActor::TLoggerActor(TIntrusivePtr<NLog::TSettings> settings,
                               TAutoPtr<TLogBackend> logBackend,
                               std::shared_ptr<NMonitoring::TMetricRegistry> metrics)
        : TActor(&TLoggerActor::StateFunc)
        , Settings(settings)
        , LogBackend(logBackend.Release())
        , Metrics(std::make_unique<TLoggerMetrics>(metrics))
    {
    }

    TLoggerActor::TLoggerActor(TIntrusivePtr<NLog::TSettings> settings,
                               std::shared_ptr<TLogBackend> logBackend,
                               std::shared_ptr<NMonitoring::TMetricRegistry> metrics)
        : TActor(&TLoggerActor::StateFunc)
        , Settings(settings)
        , LogBackend(logBackend)
        , Metrics(std::make_unique<TLoggerMetrics>(metrics))
    {
    }

    TLoggerActor::~TLoggerActor() {
    }

    void TLoggerActor::Log(TInstant time, NLog::EPriority priority, NLog::EComponent component, const char* c, ...) {
        Metrics->IncDirectMsgs();
        if (Settings && Settings->Satisfies(priority, component, 0ull)) {
            va_list params;
            va_start(params, c);
            TString formatted;
            vsprintf(formatted, c, params);

            auto ok = OutputRecord(time, NLog::EPrio(priority), component, formatted);
            Y_UNUSED(ok);
            va_end(params);
        }
    }

    void TLoggerActor::Throttle(const NLog::TSettings& settings) {
        // throttling via Sleep was removed since it causes unexpected
        // incidents when users try to set AllowDrop=false.
        Y_UNUSED(settings);
    }

    void TLoggerActor::LogIgnoredCount(TInstant now) {
        TString message = Sprintf("Ignored IgnoredCount# %" PRIu64 " log records due to logger overflow!", IgnoredCount);
        if (!OutputRecord(now, NActors::NLog::EPrio::Error, Settings->LoggerComponent, message)) {
            BecomeDefunct();
        }
    }

    void TLoggerActor::HandleIgnoredEvent(TLogIgnored::TPtr& ev, const NActors::TActorContext& ctx) {
        Y_UNUSED(ev);
        LogIgnoredCount(ctx.Now());
        IgnoredCount = 0;
        PassedCount = 0;
    }

    void TLoggerActor::HandleIgnoredEventDrop() {
        // logger backend is unavailable, just ignore
    }

    void TLoggerActor::WriteMessageStat(const NLog::TEvLog& ev) {
        Metrics->IncActorMsgs();

        const auto prio = ev.Level.ToPrio();

        switch (prio) {
            case ::NActors::NLog::EPrio::Alert:
                Metrics->IncAlertMsgs();
                break;
            case ::NActors::NLog::EPrio::Emerg:
                Metrics->IncEmergMsgs();
                break;
            default:
                break;
        }

    }

    void TLoggerActor::HandleLogEvent(NLog::TEvLog::TPtr& ev, const NActors::TActorContext& ctx) {
        i64 delayMillisec = (ctx.Now() - ev->Get()->Stamp).MilliSeconds();
        WriteMessageStat(*ev->Get());
        if (Settings->AllowDrop) {
            // Check if some records have to be dropped
            if ((PassedCount > 10 && delayMillisec > (i64)Settings->TimeThresholdMs) || IgnoredCount > 0) {
                Metrics->IncIgnoredMsgs();
                if (IgnoredCount == 0) {
                    ctx.Send(ctx.SelfID, new TLogIgnored());
                }
                ++IgnoredCount;
                PassedCount = 0;
                return;
            }
            PassedCount++;
        }

        const auto prio = ev->Get()->Level.ToPrio();
        if (!OutputRecord(ev->Get()->Stamp, prio, ev->Get()->Component, ev->Get()->Line)) {
            BecomeDefunct();
        }
    }

    void TLoggerActor::BecomeDefunct() {
        Become(&TThis::StateDefunct);
        Schedule(WakeupInterval, new TEvents::TEvWakeup);
    }

    void TLoggerActor::HandleLogComponentLevelRequest(TLogComponentLevelRequest::TPtr& ev, const NActors::TActorContext& ctx) {
        Metrics->IncLevelRequests();
        TString explanation;
        int code = Settings->SetLevel(ev->Get()->Priority, ev->Get()->Component, explanation);
        ctx.Send(ev->Sender, new TLogComponentLevelResponse(code, explanation));
    }

    void TLoggerActor::RenderComponentPriorities(IOutputStream& str) {
        using namespace NLog;
        HTML(str) {
            TAG(TH4) {
                str << "Priority Settings for the Components";
            }
            TABLE_SORTABLE_CLASS("table") {
                TABLEHEAD() {
                    TABLER() {
                        TABLEH() {
                            str << "Component";
                        }
                        TABLEH() {
                            str << "Level";
                        }
                        TABLEH() {
                            str << "Sampling Level";
                        }
                        TABLEH() {
                            str << "Sampling Rate";
                        }
                    }
                }
                TABLEBODY() {
                    for (EComponent i = Settings->MinVal; i < Settings->MaxVal; i++) {
                        auto name = Settings->ComponentName(i);
                        if (!*name)
                            continue;
                        NLog::TComponentSettings componentSettings = Settings->GetComponentSettings(i);

                        TABLER() {
                            TABLED() {
                                str << "<a href='logger?c=" << i << "'>" << name << "</a>";
                            }
                            TABLED() {
                                str << PriorityToString(EPrio(componentSettings.Raw.X.Level));
                            }
                            TABLED() {
                                str << PriorityToString(EPrio(componentSettings.Raw.X.SamplingLevel));
                            }
                            TABLED() {
                                str << componentSettings.Raw.X.SamplingRate;
                            }
                        }
                    }
                }
            }
        }
    }

    /*
     * Logger INFO:
     * 1. Current priority settings from components
     * 2. Number of log messages (via actors events, directly)
     * 3. Number of messages per components, per priority
     * 4. Log level changes (last N changes)
     */
    void TLoggerActor::HandleMonInfo(NMon::TEvHttpInfo::TPtr& ev, const TActorContext& ctx) {
        const auto& params = ev->Get()->Request.GetParams();
        NLog::EComponent component = NLog::InvalidComponent;
        NLog::EPriority priority = NLog::PRI_DEBUG;
        NLog::EPriority samplingPriority = NLog::PRI_DEBUG;
        ui32 samplingRate = 0;
        bool hasComponent = false;
        bool hasPriority = false;
        bool hasSamplingPriority = false;
        bool hasSamplingRate = false;
        bool hasAllowDrop = false;
        int allowDrop = 0;
        if (params.Has("c")) {
            if (TryFromString(params.Get("c"), component) && (component == NLog::InvalidComponent || Settings->IsValidComponent(component))) {
                hasComponent = true;
                if (params.Has("p")) {
                    int rawPriority;
                    if (TryFromString(params.Get("p"), rawPriority) && NLog::TSettings::IsValidPriority((NLog::EPriority)rawPriority)) {
                        priority = (NLog::EPriority)rawPriority;
                        hasPriority = true;
                    }
                }
                if (params.Has("sp")) {
                    int rawPriority;
                    if (TryFromString(params.Get("sp"), rawPriority) && NLog::TSettings::IsValidPriority((NLog::EPriority)rawPriority)) {
                        samplingPriority = (NLog::EPriority)rawPriority;
                        hasSamplingPriority = true;
                    }
                }
                if (params.Has("sr")) {
                    if (TryFromString(params.Get("sr"), samplingRate)) {
                        hasSamplingRate = true;
                    }
                }
            }
        }
        if (params.Has("allowdrop")) {
            if (TryFromString(params.Get("allowdrop"), allowDrop)) {
                hasAllowDrop = true;
            }
        }

        TStringStream str;
        if (hasComponent && !hasPriority && !hasSamplingPriority && !hasSamplingRate) {
            NLog::TComponentSettings componentSettings = Settings->GetComponentSettings(component);
            ui32 samplingRate = componentSettings.Raw.X.SamplingRate;
            HTML(str) {
                DIV_CLASS("row") {
                    DIV_CLASS("col-md-12") {
                        TAG(TH4) {
                            str << "Current log settings for " << Settings->ComponentName(component) << Endl;
                        }
                        UL() {
                            LI() {
                                str << "Priority: "
                                    << NLog::PriorityToString(NLog::EPrio(componentSettings.Raw.X.Level));
                            }
                            LI() {
                                str << "Sampling priority: "
                                    << NLog::PriorityToString(NLog::EPrio(componentSettings.Raw.X.SamplingLevel));
                            }
                            LI() {
                                str << "Sampling rate: "
                                    << samplingRate;
                            }
                        }
                    }
                }

                DIV_CLASS("row") {
                    DIV_CLASS("col-md-12") {
                        TAG(TH4) {
                            str << "Change priority" << Endl;
                        }
                        UL() {
                            for (int p = NLog::PRI_EMERG; p <= NLog::PRI_TRACE; ++p) {
                                LI() {
                                    str << "<a href='logger?c=" << component << "&p=" << p << "'>"
                                        << NLog::PriorityToString(NLog::EPrio(p)) << "</a>";
                                }
                            }
                        }
                        TAG(TH4) {
                            str << "Change sampling priority" << Endl;
                        }
                        UL() {
                            for (int p = NLog::PRI_EMERG; p <= NLog::PRI_TRACE; ++p) {
                                LI() {
                                    str << "<a href='logger?c=" << component << "&sp=" << p << "'>"
                                        << NLog::PriorityToString(NLog::EPrio(p)) << "</a>";
                                }
                            }
                        }
                        TAG(TH4) {
                            str << "Change sampling rate" << Endl;
                        }
                        str << "<form method=\"GET\">" << Endl;
                        str << "Rate: <input type=\"number\" name=\"sr\" value=\"" << samplingRate << "\"/>" << Endl;
                        str << "<input type=\"hidden\" name=\"c\" value=\"" << component << "\">" << Endl;
                        str << "<input class=\"btn btn-primary\" type=\"submit\" value=\"Change\"/>" << Endl;
                        str << "</form>" << Endl;
                        TAG(TH4) {
                            str << "<a href='logger'>Cancel</a>" << Endl;
                        }
                    }
                }
            }

        } else {
            TString explanation;
            if (hasComponent && hasPriority) {
                Settings->SetLevel(priority, component, explanation);
            }
            if (hasComponent && hasSamplingPriority) {
                Settings->SetSamplingLevel(samplingPriority, component, explanation);
            }
            if (hasComponent && hasSamplingRate) {
                Settings->SetSamplingRate(samplingRate, component, explanation);
            }
            if (hasAllowDrop) {
                Settings->SetAllowDrop(allowDrop);
            }

            HTML(str) {
                if (!explanation.empty()) {
                    DIV_CLASS("row") {
                        DIV_CLASS("col-md-12 alert alert-info") {
                            str << explanation;
                        }
                    }
                }

                DIV_CLASS("row") {
                    DIV_CLASS("col-md-6") {
                        RenderComponentPriorities(str);
                    }
                    DIV_CLASS("col-md-6") {
                        TAG(TH4) {
                            str << "Change priority for all components";
                        }
                        TABLE_CLASS("table table-condensed") {
                            TABLEHEAD() {
                                TABLER() {
                                    TABLEH() {
                                        str << "Priority";
                                    }
                                }
                            }
                            TABLEBODY() {
                                for (int p = NLog::PRI_EMERG; p <= NLog::PRI_TRACE; ++p) {
                                    TABLER() {
                                        TABLED() {
                                            str << "<a href = 'logger?c=-1&p=" << p << "'>"
                                                << NLog::PriorityToString(NLog::EPrio(p)) << "</a>";
                                        }
                                    }
                                }
                            }
                        }
                        TAG(TH4) {
                            str << "Change sampling priority for all components";
                        }
                        TABLE_CLASS("table table-condensed") {
                            TABLEHEAD() {
                                TABLER() {
                                    TABLEH() {
                                        str << "Priority";
                                    }
                                }
                            }
                            TABLEBODY() {
                                for (int p = NLog::PRI_EMERG; p <= NLog::PRI_TRACE; ++p) {
                                    TABLER() {
                                        TABLED() {
                                            str << "<a href = 'logger?c=-1&sp=" << p << "'>"
                                                << NLog::PriorityToString(NLog::EPrio(p)) << "</a>";
                                        }
                                    }
                                }
                            }
                        }
                        TAG(TH4) {
                            str << "Change sampling rate for all components";
                        }
                        str << "<form method=\"GET\">" << Endl;
                        str << "Rate: <input type=\"number\" name=\"sr\" value=\"0\"/>" << Endl;
                        str << "<input type=\"hidden\" name=\"c\" value=\"-1\">" << Endl;
                        str << "<input class=\"btn btn-primary\" type=\"submit\" value=\"Change\"/>" << Endl;
                        str << "</form>" << Endl;
                        TAG(TH4) {
                            str << "Drop log entries in case of overflow: "
                                << (Settings->AllowDrop ? "Enabled" : "Disabled");
                        }
                        str << "<form method=\"GET\">" << Endl;
                        str << "<input type=\"hidden\" name=\"allowdrop\" value=\"" << (Settings->AllowDrop ? "0" : "1") << "\"/>" << Endl;
                        str << "<input class=\"btn btn-primary\" type=\"submit\" value=\"" << (Settings->AllowDrop ? "Disable" : "Enable") << "\"/>" << Endl;
                        str << "</form>" << Endl;
                    }
                }
                Metrics->GetOutputHtml(str);
            }
        }

        ctx.Send(ev->Sender, new NMon::TEvHttpInfoRes(str.Str()));
    }

    constexpr size_t TimeBufSize = 512;

    bool TLoggerActor::OutputRecord(TInstant time, NLog::EPrio priority, NLog::EComponent component,
                                    const TString& formatted) noexcept try {
        const auto logPrio = ::ELogPriority(ui16(priority));

        char buf[TimeBufSize];
        switch (Settings->Format) {
            case NActors::NLog::TSettings::PLAIN_FULL_FORMAT: {
                TStringBuilder logRecord;
                if (Settings->UseLocalTimestamps) {
                    logRecord << FormatLocalTimestamp(time, buf);
                } else {
                    logRecord << time;
                }
                logRecord
                    << Settings->MessagePrefix
                    << " :" << Settings->ComponentName(component)
                    << " "  << PriorityToString(priority)
                    << ": " << formatted;
                LogBackend->WriteData(
                    TLogRecord(logPrio, logRecord.data(), logRecord.size()));
            } break;

            case NActors::NLog::TSettings::PLAIN_SHORT_FORMAT: {
                TStringBuilder logRecord;
                logRecord
                    << Settings->ComponentName(component)
                    << ": " << formatted;
                LogBackend->WriteData(
                    TLogRecord(logPrio, logRecord.data(), logRecord.size()));
            } break;

            case NActors::NLog::TSettings::JSON_FORMAT: {
                NJsonWriter::TBuf json;
                json.BeginObject()
                    .WriteKey("@timestamp")
                    .WriteString(Settings->UseLocalTimestamps ? FormatLocalTimestamp(time, buf) : time.ToString().data())
                    .WriteKey("microseconds")
                    .WriteULongLong(time.MicroSeconds())
                    .WriteKey("host")
                    .WriteString(Settings->ShortHostName)
                    .WriteKey("cluster")
                    .WriteString(Settings->ClusterName)
                    .WriteKey("priority")
                    .WriteString(PriorityToString(priority))
                    .WriteKey("npriority")
                    .WriteInt((int)priority)
                    .WriteKey("component")
                    .WriteString(Settings->ComponentName(component))
                    .WriteKey("tag")
                    .WriteString("KIKIMR")
                    .WriteKey("revision")
                    .WriteInt(GetProgramSvnRevision())
                    .WriteKey("message")
                    .WriteString(formatted)
                    .EndObject();
                auto logRecord = json.Str();
                LogBackend->WriteData(
                    TLogRecord(logPrio, logRecord.data(), logRecord.size()));
            } break;
        }

        return true;
    } catch (...) {
        return false;
    }

    void TLoggerActor::HandleLogEventDrop(const NLog::TEvLog::TPtr& ev) {
        WriteMessageStat(*ev->Get());
        Metrics->IncDroppedMsgs();
    }

    void TLoggerActor::HandleWakeup() {
        Become(&TThis::StateFunc);
    }

    const char* TLoggerActor::FormatLocalTimestamp(TInstant time, char* buf) {
        struct tm localTime;
        time.LocalTime(&localTime);
        int r = strftime(buf, TimeBufSize, "%Y-%m-%d-%H-%M-%S", &localTime);
        Y_VERIFY(r != 0);
        return buf;
    }

    TAutoPtr<TLogBackend> CreateSysLogBackend(const TString& ident,
                                              bool logPError, bool logCons) {
        int flags = 0;
        if (logPError)
            flags |= TSysLogBackend::LogPerror;
        if (logCons)
            flags |= TSysLogBackend::LogCons;

        return new TSysLogBackend(ident.data(), TSysLogBackend::TSYSLOG_LOCAL1, flags);
    }

    class TStderrBackend: public TLogBackend {
    public:
        TStderrBackend() {
        }
        void WriteData(const TLogRecord& rec) override {
#ifdef _MSC_VER
            if (IsDebuggerPresent()) {
                TString x;
                x.reserve(rec.Len + 2);
                x.append(rec.Data, rec.Len);
                x.append('\n');
                OutputDebugString(x.c_str());
            }
#endif
            bool isOk = false;
            do {
                try {
                    TRecordWithNewline r(rec);
                    Cerr.Write(r.Buf.Data(), r.Buf.Filled());
                    isOk = true;
                } catch (TSystemError err) {
                    // Interrupted system call
                    Y_UNUSED(err);
                }
            } while (!isOk);
        }

        void ReopenLog() override {
        }

    private:
        const TString Indent;
    };

    class TLineFileLogBackend: public TFileLogBackend {
    public:
        TLineFileLogBackend(const TString& path)
            : TFileLogBackend(path)
        {
        }

        // Append newline after every record
        void WriteData(const TLogRecord& rec) override {
            TFileLogBackend::WriteData(TRecordWithNewline(rec));
        }
    };

    class TCompositeLogBackend: public TLogBackend {
    public:
        TCompositeLogBackend(TVector<TAutoPtr<TLogBackend>>&& underlyingBackends)
            : UnderlyingBackends(std::move(underlyingBackends))
        {
        }

        void WriteData(const TLogRecord& rec) override {
            for (auto& b: UnderlyingBackends) {
                b->WriteData(rec);
            }
        }

        void ReopenLog() override {
        }

    private:
        TVector<TAutoPtr<TLogBackend>> UnderlyingBackends;
    };

    TAutoPtr<TLogBackend> CreateStderrBackend() {
        return new TStderrBackend();
    }

    TAutoPtr<TLogBackend> CreateFileBackend(const TString& fileName) {
        return new TLineFileLogBackend(fileName);
    }

    TAutoPtr<TLogBackend> CreateNullBackend() {
        return new TNullLogBackend();
    }

    TAutoPtr<TLogBackend> CreateCompositeLogBackend(TVector<TAutoPtr<TLogBackend>>&& underlyingBackends) {
        return new TCompositeLogBackend(std::move(underlyingBackends));
    }
}