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

标签 c# events console-application overlapping console.writeline

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

但是我已经遭受登录控制台的困扰,当几乎同时发生 2 次攻击时,控制台输出“重叠”,如下所示:

enter image description here

用简约的代码来展示我基本上所做的事情:

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/

相关文章:

c# - 在 WPF MVVM 应用程序中管理 DbContext

c# - 在没有完整回发的情况下获取查询字符串值

angularjs - 用户刷新浏览器时 $stateChangeStart 不起作用

javascript - 在元素上引发 mousemove 事件

python-3.x - 实时更新 Python 中的可执行子进程控制台输出

c# - 如何检查对象是否已更改?

c# - DbMigrationsConfiguration 如何与 EF 中的 DbMigration 相关

swing - 为什么 JScrollPane 不对鼠标滚轮事件使用react?

c++ - 为 C++ 库集成 python 脚本控制台

c# - 将引号字符 (") 作为 C# 控制台应用程序参数传递