如何处理触发事件中重叠的 Console.Writeline()?

How to handle overlapping Console.Writeline()'s from fired Event?

嘿,我正在为我拥有的 windows 服务器编写 RDP 蛮力保护程序,它甚至在更改 RDP 端口后受到攻击:/

但我已经在登录控制台时遇到了问题,当几乎同时有 2 次攻击时,控制台输出 "overlaps" 如:

简单的代码来展示我基本上做了什么:

watcher.EventRecordWritten +=
                new EventHandler<EventRecordWrittenEventArgs>(EventLogEventRead);

public static async void EventLogEventRead(object obj,
        EventRecordWrittenEventArgs arg)
    {            
        if (arg.EventRecord != null)
        {
            string IP = GetIPFromRecord(arg.EventRecord)

            var json = await new HttpClient().GetStringAsync("https://api.ipgeolocationapi.com/geolocate/" + IP);
            var jsonDeserialized = new JavaScriptSerializer().Deserialize<dynamic>(json);
            string country = jsonDeserialized["name"];


            Console.WriteLine("IP:\t" + IP);
            Console.WriteLine("Country:\t" + country);
        }
        else
        {
            Console.WriteLine("The event instance was null.");
        }
    }

完整代码(没有错误消息Class):Pastebin

那么解决这样的问题最优雅的方法是什么?

它重叠是因为您对单个日志条目多次调用 Console.WriteLine()。您需要准备好整个输出主体并立即将其写入控制台。

例如改

Console.WriteLine("IP:\t" + IP);
Console.WriteLine("Country:\t" + country);

var msg = $"IP:\t{IP}{Environment.NewLine}Country:\t{country}";
Console.WriteLine(msg);

或者更好,使用 StringBuilder:

var builder = new StringBuilder();
builder.AppendLine($"IP:\t{IP}");
builder.AppendLine($"Country:\t{country}");
Console.WriteLine(builder.ToString());

我还可以推荐使用专门的日志记录框架,例如 NLog (https://github.com/NLog/NLog)。您仍然需要如上所述立即编写条目,但它可以帮助您设置样式输出并在将来需要时轻松添加其他目标(文件、网络等)。

你应该使用一把锁:

watcher.EventRecordWritten +=
                new EventHandler<EventRecordWrittenEventArgs>(EventLogEventRead);


private static readonly object myLock = new object();

public static async void EventLogEventRead(object obj, EventRecordWrittenEventArgs arg)
{          

    if (arg.EventRecord != null)
    {
        string IP = GetIPFromRecord(arg.EventRecord)

        var json = await new HttpClient().GetStringAsync("https://api.ipgeolocationapi.com/geolocate/" + IP);
        var jsonDeserialized = new JavaScriptSerializer().Deserialize<dynamic>(json);
        string country = jsonDeserialized["name"];

        lock (myLock) {
            Console.WriteLine("IP:\t" + IP);
            Console.WriteLine("Country:\t" + country);
        }
    }
    else
    {   
        lock (myLock) {
            Console.WriteLine("The event instance was null.");
        }
    }

}