Thank you for the output. That makes things much clearer.
I suspect the ^M were always there, but since all of the lines had them, vi assumed DOS line endings and suppressed them. But, once you added the header with only the line feed, it thought it had unix line endings and showed all of the ^M's. If I am correct, the solution is to replace \n in the header with \r\n like this
my $header = "\r\n\r\n======= system =======\r\n";
To get the word "system" change to the actual system name in the log file, replace the line
my $my_header = $header;
$my_header =~ s/system/$system/;
I hope this helps. Let me know what happens.