Search code examples
c#eventsconsole-applicationoverlappingconsole.writeline

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


Hey i am programming a RDP Bruteforce Protection program for a windows server i own, which even gets attacked after changing the RDP port :/

But i already suffer from logging in console, when there are 2 attacks at mostly same time, the console output "overlaps" like:

enter image description here

Minimalistic code to show what i do basically:

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.");
        }
    }

Full code (without Error Messages Class): Pastebin

So what is the most elegant way to solve such a problem?


Solution

  • It overlaps because you have multiple calls of Console.WriteLine() for single log entry. You need to prepare whole output body and write it to console at once.

    For example, change

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

    to

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

    Or even better, use StringBuilder:

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

    Also I could recommend to use specialized logging framework, for example NLog (https://github.com/NLog/NLog). You will still need to write entries at once as described above, but it could help you with styling output and easily add other targets (files, network, etc) in future if required.