Skip to content

Instantly share code, notes, and snippets.

@kentcb
Last active June 21, 2016 02:17
Show Gist options
  • Save kentcb/5e0840a98d15dfa0e156c59a70436499 to your computer and use it in GitHub Desktop.
Save kentcb/5e0840a98d15dfa0e156c59a70436499 to your computer and use it in GitHub Desktop.
Quick and dirty logging
namespace Logging
{
using System;
using System.Diagnostics;
using System.Threading;
public static class Log
{
public static Action<string> LogSink
{
get;
set;
}
public static void Info(string message)
{
LogSink("[INFO] " + message);
}
public static void Info(string format, params object[] args)
{
LogSink("[INFO] " + string.Format(format, args));
}
public static PerfBlock Perf(string message)
{
return new PerfBlock(message);
}
public static PerfBlock Perf(string format, params object[] args)
{
return new PerfBlock(string.Format(format, args));
}
public struct PerfBlock : IDisposable
{
private static int nextLevel;
private readonly string message;
private readonly Stopwatch stopwatch;
private readonly int level;
public PerfBlock(string message)
{
this.message = message;
this.stopwatch = Stopwatch.StartNew();
this.level = Interlocked.Increment(ref nextLevel);
}
public void Dispose()
{
this.stopwatch.Stop();
Log.LogSink($"[PERF] {new string(' ', this.level * 4)} {this.message} [{this.stopwatch.ElapsedMilliseconds}ms]");
Interlocked.Decrement(ref nextLevel);
}
}
}
}
@kentcb
Copy link
Author

kentcb commented May 11, 2016

Stupid little thing I can throw into a project when I'm just trying to get some perf diagnostics from areas of the code base that don't have any decent logging infrastructure.

Obviously requires the platform to assign an action to LogSink, which usually just writes to Console.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment