Last active
May 17, 2021 12:43
-
-
Save Pzixel/b851e3955cb9cec8b1b429a4fa876210 to your computer and use it in GitHub Desktop.
Faster logging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var logger = new MyLogger(); | |
var sw = Stopwatch.StartNew(); | |
for (int i = 0; i < 50000; i++) | |
{ | |
logger.Print("{'Timestamp':'" + DateTimeOffset.Now.ToString("o") + "','Level':'Information','MessageTemplate':'Hello, {@User}, {N} at {Now}','Properties':{'User':{'Name':'nblumhardt','Tags':[1,2,3]},'N':555,'Now':'2021-05-17T14:51:13.8962062+03:00'}}\n"); | |
} | |
Console.WriteLine(sw.Elapsed); | |
Thread.Sleep(5000); | |
} | |
} | |
class MyLogger | |
{ | |
public void Print(string message) | |
{ | |
Console.Write(message); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var logger = new MyLogger(); | |
var sw = Stopwatch.StartNew(); | |
for (int i = 0; i < 50000; i++) | |
{ | |
logger.Print("{'Timestamp':'" + DateTimeOffset.Now.ToString("o") + "','Level':'Information','MessageTemplate':'Hello, {@User}, {N} at {Now}','Properties':{'User':{'Name':'nblumhardt','Tags':[1,2,3]},'N':555,'Now':'2021-05-17T14:51:13.8962062+03:00'}}\n"); | |
} | |
Console.WriteLine(sw.Elapsed); | |
Thread.Sleep(5000); | |
} | |
} | |
class MyLogger | |
{ | |
private volatile StringBuilder _buffer = new(80000); | |
public MyLogger() | |
{ | |
RunJob(); | |
} | |
public void Print(string message) | |
{ | |
_buffer.Append(message); | |
} | |
private void RunJob() | |
{ | |
_ = Task.Run(async () => | |
{ | |
while (true) | |
{ | |
if (_buffer.Length > 0) | |
{ | |
StringBuilder buffer; | |
lock (_buffer) | |
{ | |
buffer = _buffer; | |
_buffer = new(80000); | |
} | |
var output = Console.Out; | |
await output.WriteAsync(buffer.ToString()); | |
await output.FlushAsync(); | |
} | |
else | |
{ | |
Console.WriteLine($"Maybe ended {DateTime.Now:o}"); | |
await Task.Delay(500); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment