嘿,我正在为我拥有的 Windows 服务器编写 RDP 暴力保护程序,该程序甚至在更改 RDP 端口后受到攻击:/
但是我已经遭受登录控制台的困扰,当几乎同时发生 2 次攻击时,控制台输出“重叠”,如下所示:
用简约的代码来展示我基本上所做的事情:
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.");
}
}
完整代码(没有错误消息类):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 )。您仍然需要如上所述立即编写条目,但它可以帮助您设计输出样式,并在将来根据需要轻松添加其他目标(文件、网络等)。
关于c# - 如何处理触发事件中重叠的 Console.Writeline()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59474714/